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

關(guān)于iOS中動作傳輸問題。

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

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

.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];  
}  
  

**主函數(shù)中使用 **


 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參數(shù),并在類中引用。

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)
    ...
   }
}

主函數(shù)中使用

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!!!"
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • __block和__weak修飾符的區(qū)別其實是挺明顯的:1.__block不管是ARC還是MRC模式下都可以使用,...
    LZM輪回閱讀 3,594評論 0 6
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,057評論 25 709
  • iOS面試小貼士 ———————————————回答好下面的足夠了------------------------...
    不言不愛閱讀 2,251評論 0 7
  • 多線程、特別是NSOperation 和 GCD 的內(nèi)部原理。運行時機制的原理和運用場景。SDWebImage的原...
    LZM輪回閱讀 2,120評論 0 12
  • 工作結(jié)束一大早七點出發(fā)從廣州飛到西安,然后在機場消磨了近五個小時等晚點的伙伴,再驅(qū)車三個多小時,到晚上七點才來到太...
    真言臻宇閱讀 262評論 0 1

友情鏈接更多精彩內(nèi)容