控制器中的 UIView 触摸事件

118

我该如何在编程中添加UIView的touchbegin动作或touchend动作,因为Xcode没有从Main.storyboard提供此功能?


2
那个是针对按钮的,OP想要为UIView添加事件。 - Miknash
1
使用 UILongPressGestureRecognizer,并将 minimumPressDuration 设置为零。请参见此答案。 不需要子类化或覆盖任何内容。 - Suragch
11个回答

2

针对Swift 4.x更新@stevo.mit的答案:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接