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!!!"
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • __block和__weak修饰符的区别其实是挺明显的:1.__block不管是ARC还是MRC模式下都可以使用,...
    LZM轮回阅读 3,407评论 0 6
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,002评论 25 709
  • iOS面试小贴士 ———————————————回答好下面的足够了------------------------...
    不言不爱阅读 2,023评论 0 7
  • 多线程、特别是NSOperation 和 GCD 的内部原理。运行时机制的原理和运用场景。SDWebImage的原...
    LZM轮回阅读 2,046评论 0 12
  • 工作结束一大早七点出发从广州飞到西安,然后在机场消磨了近五个小时等晚点的伙伴,再驱车三个多小时,到晚上七点才来到太...
    真言臻宇阅读 237评论 0 1