iOS Button快捷处理点击事件 与View快捷处理添加单击手势(一)

实际开发中,button添加点击事件的时候是这样色的

  let button = UIButton()
        button.addTarget(self, action: #selector(buttonClick), for:.touchUpInside)
func buttonClick({
        //你的爆炸操作
        })

加上扩展之后(整容后)

  let button = UIButton()
        button.addTouchClosure { 
            //是时候展现真正的技术了
        }
        

是不是感觉方便快捷美滋滋,好了废话不多说,直接上代码,粘去直接用(建个Swift文件直接复制上去就行了)

import Foundation
import UIKit

public extension UIButton{
      private struct AssociatedKeys{
             static var buttonTouch  = "buttonTouch"
           }
    
    
     typealias TouchedClosure = ()->Void
    
   public func addTouchClosure(closure:TouchedClosure?) {
          objc_setAssociatedObject(self,&AssociatedKeys.buttonTouch,closure,.OBJC_ASSOCIATION_COPY_NONATOMIC)
        self.addTarget(self, action:#selector(actionTouch), for: UIControlEvents.touchUpInside)
    }
  @objc private   func actionTouch(){
        if let closure:TouchedClosure = objc_getAssociatedObject(self,&AssociatedKeys.buttonTouch) as? UIButton.TouchedClosure{
            closure()
        }
        
    }
 }

这边再给个OC版好了
UIButton+Block.h文件中

#import 
typedef void (^TouchedBlock)();

@interface UIButton (Block)
-(void)addActionHandler:(TouchedBlock)touchHandler;
@end

UIButton+Block.m文件中

#import "UIButton+Block.h"
#import 
static const void *UIButtonBlockKey = &UIButtonBlockKey;

@implementation UIButton (Block)
-(void)addActionHandler:(TouchedBlock)touchHandler{
    objc_setAssociatedObject(self, UIButtonBlockKey, touchHandler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(actionTouched:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)actionTouched:(UIButton *)btn{
    TouchedBlock block = objc_getAssociatedObject(self, UIButtonBlockKey);
    if (block) {
        block();
    }
}
@end

你可能感兴趣的:(iOS Button快捷处理点击事件 与View快捷处理添加单击手势(一))