长按手势事件:
长按按钮1S后改变按钮颜色:
1 // 长按事件 2 #import "ViewController.h" 3 @interface ViewController (){ 4 UIButton *myBtn; 5 } 6 @end 7 @implementation ViewController 8 - (void)viewDidLoad { 9 [super viewDidLoad]; 10 myBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 200, 214, 80)]; 11 myBtn.backgroundColor = [UIColor orangeColor]; 12 [myBtn setTitle:@"开始按钮" forState:UIControlStateNormal]; 13 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];//初始化一个长按手势 14 [longPress setMinimumPressDuration:1];//设置按多久之后触发事件 15 [myBtn addGestureRecognizer:longPress];//把长按手势添加给按钮 16 [self.view addSubview:myBtn]; 17 } 18 -(void)longPressAction:(UILongPressGestureRecognizer*)sender{ 19 // UIGestureRecognizerStatePossible,按钮state的各种枚举值 20 // UIGestureRecognizerStateBegan, 21 // UIGestureRecognizerStateChanged, 22 // UIGestureRecognizerStateEnded, 23 // UIGestureRecognizerStateCancelled, 24 // UIGestureRecognizerStateFailed, 25 // UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded 26 if (sender.state == UIGestureRecognizerStateBegan) { 27 myBtn.backgroundColor = [UIColor greenColor];//当状态为Began时,触发事件(修改btn的背景色) 28 } 29 } 30 @end
时间: 2024-10-07 03:37:59