Objective C中target: action使用以及swift中@selector使用

關於iOS中動作傳輸問題。

0x01.Objective C中動作傳輸問題

新建一個UIView類,上面定義了很多按鈕,如何給每個按鈕添加一個動作,並在主函數中實現點擊使用呢?下面給出兩種語言的傳輸方法。

.h

@interface TargetActionView : UIView  

@property(nonatomic,assign)id target;  //定義屬性  
@property(nonatomic,assign) SEL action;  
  
-(id)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action;//初始化方法  
  
@end  
  

.m

  
#import "TargetActionView.h"  
  
@implementation TargetActionView  
  
- (id)initWithFrame:(CGRect)frame  
{  
    self = [super initWithFrame:frame];  
    if (self) {  
        // Initialization code  
    }  
    return self;  
}  
  
-(id)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action  
{  
    self=[super initWithFrame:frame];  
    if (self) {  
        _target=target;  
        _action=action;  
    }  
    return self;  
}  
  
//touchesBegan方法  
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    [_target performSelector:_action withObject:self];  
}  
  

**主函數中使用 **


 TargetActionView *targetActionView=[[TargetActionView alloc]initWithFrame:CGRectMake(30, 30, 130, 130) target:self action:@selector(changColor:)];  
    targetActionView.backgroundColor=[UIColor redColor];  
    [self.view addSubview:targetActionView];  
    // Do any additional setup after loading the view.  
}  
  
-(void)changColor:(TargetActionView *)color  
{  
    color.backgroundColor=[UIColor orangeColor];  
}  

0x02.swift中動作傳輸問題

直接在初始化的時候傳入selector:Selector參數,並在類中引用。

class ShareMoreView: UIView{
    convenience init(frame: CGRect,selector:Selector,target:AnyObject) {
    ...
    let button = UIButton(type:.custom)
    button.tag = i+1
    button.addTarget(target, action: selector, for: .touchUpInside)
    ...
   }
}

主函數中使用

shareView = ShareMoreView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), selector: #selector(ViewController.shareMoreClick(_:)), target: self)
func shareMoreClick(_ button:UIButton){
   print "this is test!!!"
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章