
输入
|
87
3.1
侦测触摸
问题
我们如何知道用户触摸了某个视图?
解决方案
我们可以覆盖几个
UIView
的方法,这样当触摸开始、移动和结束时,这些方法将
得到调用。
在
View Controller
或
UIView
子类中加入以下代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
NSLog("A touch began at \(touch.location(in: self.view))")
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
NSLog("A touch moved at \(touch.location(in: self.view))")
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
NSLog("A touch ended at \(touch.location(in: self.view))")
}
}
override func touchesCancelled(_ touches: ...