2016-11-26 21 views
0

我想檢測UITouch事件visible.When begins.Currently觸摸事件,我使用下面的代碼來檢測下面的代碼觸摸location.From,我也能打印觸摸location.Any,幫助將不勝感激。如何檢測斯威夫特UITouch位置可見3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{ 
    if let touch = touches.first { 
     let position :CGPoint = touch.location(in: view) 
     print(position.x) 
     print(position.y) 
    } 
} 

注:我不是畫線或類似的東西繪圖app.I,只是想看看觸摸事件發生visibly.When。

在此先感謝。

+0

你的意思是你想畫一個圓或什麼東西來表明觸摸的位置? – Sweeper

回答

1

如果你想有一個圓或東西,當用戶點擊屏幕出現,試試這個:

var touchIndicators: [UIView] = [] 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for touch in touches { 
     let location = touch.location(in: view) 
     let touchIndicator = UIView(frame: CGRect(x: location.x - 10, y: location.y - 10, width: 20, height: 20)) 
     touchIndicator.alpha = 0.5 
     touchIndicator.backgroundColor = UIColor.red 
     touchIndicator.layer.cornerRadius = 10 
     self.view.addSubview(touchIndicator) 
     touchIndicators.append(touchIndicator) 
    } 
} 

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for indicator in touchIndicators { 
     indicator.removeFromSuperview() 
    } 
    touchIndicators = [] 
} 

非常簡單。當用戶觸摸屏幕並在用戶擡起他/她的手指時將其刪除時添加圓形視圖。您也可以使用UITapGestureRecognizer來做到這一點。

+0

感謝隊友。代碼works.I想實現在'touchMoved'功能時,您的答案,但touchIndicator移動遍佈視圖expected.i想知道如何讓我的的touchIndicator(一圈)只要按照手指... – Joe

+0

@Joe如果你想要做到這一點,那麼只需刪除for循環並用'touches.first!'替換'touch'並將數組更改爲單個UIView實例。在touchesMoved中,將其框架設置到新的位置 – Sweeper