UIButton,UIGestureRecognizer,Target-Action

9 8月
  • UIButton
  • Target-Action设计模式
  • UIGestureRecognizer

UIButton

用UIButton可实现用户交互行为。和静态UILabel,UIImage等不同之处在于,UIButton因为可以实现交互,所以提供了一些基本状态enabled,selected,highlighted,每种状态下都有不同的视图。

@property(nonatomic, strong, readwrite) UIButton *deleteButton;

self.deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
[self.deleteButton setTitle:@"X" forState:UIControlStateNormal];
[self.deleteButton setTitle:@"V" forState:UIControlStateHighlighted];
self.deleteButton.layer.cornerRadius = 10;
self.deleteButton.layer.masksToBounds = YES;
self.deleteButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
self.deleteButton.layer.borderWidth = 2;

Target-Action设计模式

UIButton的点击交互使用的是Target-Action设计模式,就是调用target对象上的方法。UIButton继承自UIControl,为我们提供了addTarget方法:为宿主增加一个触发事件的条件forControlEvents,事件触发后调用target里的action

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

UIButton继承自UIControl,而UIControl继承自UIView,所以UIControl是在View的基础上封装了一层可以接受用户交互的逻辑。

[self.deleteButton addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];

-(void) deleteButtonClick {
    ...
}

UIGestureRecognizer

除了UIButton,如果想在其他UIView(例如UIImageView)上处理手势,可以用UIGestureRecognizer,它封装了一些手势:

UITapGestureRecognizer
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UILongPressGestureRecognizer

只需要创建手势,设置响应处理,在视图上注册这些手势,通过Target-Action设计模式进行处理。

@interface testViewController ()

[view addSubview:({
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick)];
    tapGesture.delegate = self;
    [view addGestureRecognizer:tapGesture];
    view;
})];

-(void) viewClick {
    ...
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    ... // 返回no就不会执行面的viewClick,这是为复杂的业务场景考虑的,例如点击view的某些区域响应手势,另一些区域不响应手势
    return NO;      
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注