長按手勢事件:
長按按鈕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