我想处理 UIButton 触摸结束时发生的事件。我知道UIControl有一些实现触摸的事件(UIControlEventTouchDown,UIControlEventTouchCancel等)。但除了 UIControlEventTouchDown 和 UIControlEventTouchUpInside 之外,我无法抓住其中任何一个。
我的按钮是一些UIView的子视图。 UIView已将 userInteractionEnabled 属性设置为 YES 。
怎么了?
答案 0 :(得分:24)
您可以根据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");
}
答案 1 :(得分:3)
您需要创建自己的扩展UIButton
的自定义类。
你的头文件应该是这样的。
@interface customButton : UIButton
{
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
然后制作您的实施文件
答案 2 :(得分:0)
我认为这更容易
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
}
}
答案 3 :(得分:0)
只需为UIButton添加IBOutlets,其中包含事件TouchDown:
和主要操作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)");
}
答案 4 :(得分:0)
@Ramshad在 Swift 3.0 语法中接受了answer 使用以下 UIControl 类
的方法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")
}
答案 5 :(得分:0)
Swift 3.0版本:
let btn = UIButton(...)
btn.addTarget(self, action: #selector(MyView.onTap(_:)), for: .touchUpInside)
func onTap(_ sender: AnyObject) -> Void {
}