我希望能够处理当UIButton触摸结束时发生的事件。我知道UIControl有一些实现触摸的事件(UIControlEventTouchDown,UIControlEventTouchCancel等),但是除了UIControlEventTouchDown和UIControlEventTouchUpInside之外,我无法捕获任何一个事件。
我的按钮是某个UIView的子视图。该UIView的userInteractionEnabled属性设置为YES。
出了什么问题?
我希望能够处理当UIButton触摸结束时发生的事件。我知道UIControl有一些实现触摸的事件(UIControlEventTouchDown,UIControlEventTouchCancel等),但是除了UIControlEventTouchDown和UIControlEventTouchUpInside之外,我无法捕获任何一个事件。
我的按钮是某个UIView的子视图。该UIView的userInteractionEnabled属性设置为YES。
出了什么问题?
根据ControlEvents
,您可以为按钮设置“操作目标”。
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
例子:
[yourButton addTarget:self
action:@selector(methodTouchDown:)
forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self
action:@selector(methodTouchUpInside:)
forControlEvents: UIControlEventTouchUpInside];
-(void)methodTouchDown:(id)sender{
NSLog(@"TouchDown");
}
-(void)methodTouchUpInside:(id)sender{
NSLog(@"TouchUpInside");
}
你需要创建一个自定义类,继承UIButton
。你的头文件应该像这样。
@interface customButton : UIButton
{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
使用UIControl类的以下方法,@Ramshad在Swift 3.0语法中接受了答案
open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents)
例子:
myButton.addTarget(self, action: #selector(MyViewController.touchDownEvent), for: .touchDown)
myButton.addTarget(self, action: #selector(MyViewController.touchUpEvent), for: [.touchUpInside, .touchUpOutside])
func touchDownEvent(_ sender: AnyObject) {
print("TouchDown")
}
func touchUpEvent(_ sender: AnyObject) {
print("TouchUp")
}
Swift 3.0 版本:
let btn = UIButton(...)
btn.addTarget(self, action: #selector(MyView.onTap(_:)), for: .touchUpInside)
func onTap(_ sender: AnyObject) -> Void {
}
我认为这更容易
UILongPressGestureRecognizer *longPressOnButton = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOnButton:)];
longPressOnButton.delegate = self;
btn.userInteractionEnabled = YES;
[btn addGestureRecognizer:longPressOnButton];
- (void)longPressOnButton:(UILongPressGestureRecognizer*)gesture
{
// When you start touch the button
if (gesture.state == UIGestureRecognizerStateBegan)
{
//start recording
}
// When you stop touch the button
if (gesture.state == UIGestureRecognizerStateEnded)
{
//end recording
}
}
只需为带有事件的UIButton添加IBOutlets TouchDown:
和Primary Action Triggered:
- (IBAction)touchDown:(id)sender {
NSLog(@"This will trigger when button is Touched");
}
- (IBAction)primaryActionTriggered:(id)sender {
NSLog(@"This will trigger Only when touch end within Button Boundary (not Frame)");
}