[英]Start touch outside a button and trigger an event when dragged into the bounds of button
If I have a button and starts a touch outside of the buttons bounds and then drag my finger across the screen until I hit the bounds of the button which then will trigger an event.如果我有一个按钮并在按钮边界之外开始触摸,然后在屏幕上拖动我的手指,直到我点击按钮的边界,然后将触发一个事件。 Say change the background color of the button for example (which I know how to).例如,说改变按钮的背景颜色(我知道怎么做)。 How do I trigger something from that type of touch movement?我如何从这种类型的触摸运动中触发某些东西?
I also set my buttons programmatically.我还以编程方式设置了我的按钮。
Thanks in advance!提前致谢!
To trigger an action attached to a button when a finger is moving over the button you can use a method touchesMoved(_:with:) of UIViewController.要在手指在按钮上移动时触发附加到按钮的操作,您可以使用 UIViewController 的touchesMoved(_:with:)方法。
Firstly, add an action to the button for touchUpInside and touchDragInside inside InterfaceBuilder or in code.首先,在 InterfaceBuilder 或代码中为touchUpInside和touchDragInside的按钮添加一个动作。
Secondly, override touchesMoved(_:with:) method and call a super.其次,覆盖 touchesMoved(_:with:)方法并调用一个超级。 If the super is not called the button UIKit will not trigger any actions on the button.如果没有调用 super 按钮,UIKit 将不会触发按钮上的任何操作。 Next, get a touch location inside the view and trigger a touchDragInside action on the button.接下来,获取视图内的触摸位置并触发按钮上的 touchDragInside 动作。
@IBOutlet weak var button: UIButton!
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if let t = touches.first,
button.frame.contains(t.location(in: view)) {
button.sendActions(for: .touchDragInside)
} else {
print("false")
}
}
@IBAction
func didTapButton() {
print("true: touch inside the frame of a button")
}
@IBAction
func didDragInsideButton() {
print("true: touch drag inside the frame of a button")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
button.addTarget(self, action: #selector(didDragInsideButton), for: .touchDragInside)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.