在UIView中添加点击事件oc及swift

UIView继承于UIResponder是没有addTarget 方法的,所有只能在UIView上添加手势UITapGestureRecognizer来实现点击事件。
首先设定UIView(或其子类)为可交互的:

oc:

iconView.userInteractionEnabled = YES;

添加tap手势:
//tap手势

UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapevent:)];

将手势添加至需要相应的view中

 [iconView addGestureRecognizer:tapGesture];

默认为单击触发事件:
设置手指个数:

 [tapGesture setNumberOfTapsRequired:1];

执行触发的方法:

- (void)tapevent:(UITapGestureRecognizer *)gesture {
 NSLog(@"单击"); 
 }

Swift:

    view.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction))
    tapGesture.numberOfTapsRequired = 1
    view.addGestureRecognizer(tapGesture)
//MARK: 点击事件
extension MeViewController{

    @objc fileprivate func tapGestureAction(){
        LGJLog("跳转个人中心")   
    }
}

你可能感兴趣的:(项目优化,swift)