当用户将手指拖入按钮区域时触发UIButton的方法?
我希望在以下条件下有一个触发其方法的按钮:
- 当用户点击按钮时
- 当用户按下按钮并将他/她的手指拖出按钮区域时
- 当用户将他/她的手指从按钮区域外拖到按钮区域内
基本上,无论触摸的原点是什么,只要触摸按钮的任何部分,我都希望触发该方法,但希望通过操作UIButton属性来完成此操作,例如touchedUpInside
等。
谢谢你的建议!
关于:
- 当用户按下按钮并将他/她的手指拖出按钮区域时
我最近做了类似的事情。 这是我在Swift中的代码。
(在此示例中,您将UIButton子类化,如: class FadingButton: UIButton
)
... // The user tapped the button and then moved the finger around. override func touchesMoved(_ touches: Set, with event: UIEvent?) { super.touchesMoved(touches, with: event) // Get the point to which the finger moved if let point: CGPoint = touches.first?.location(in: self) { // If the finger was dragged outside of the button... if ((point.x < 0 || point.x > bounds.width) || (point.y < 0 || point.y > bounds.height)) { // Do whatever you need here } } } ...
我希望它对某人有帮助。
让你的方法如-(IBAction)btnTap
并连接到这些属性
- 当用户点击按钮时。 – 使用
Touch Down
方法 - 当用户按下按钮并将他/她的手指拖出按钮的区域时 – 使用
Touch Up Inside
来实现此目的 - 当用户将他/她的手指从按钮的区域外拖到按钮的内部时 –
Touch Drag Inside
您需要将以下UIControlEvents添加到按钮:
-
UIControlEventTouchUpInside
-
UIControlEventTouchDragOutside
-
UIControlEventTouchDragInside
因此
[self.myButton addTarget:self action:@selector(dragMoving:withEvent: ) forControlEvents: UIControlEventTouchDragInside | UIControlEventTouchDragOutside]; [self.myButton addTarget:self action:@selector(dragEnded:withEvent: ) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchUpOutside]; [self.myButton addTarget:self action:@selector(myButtonTouchDown:withEvent: ) forControlEvents: UIControlEventTouchDown];