美文网首页
Objective C中target: action使用以及sw

Objective C中target: action使用以及sw

作者: 云天大侠_general | 来源:发表于2017-03-19 12:51 被阅读848次

关于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!!!"
}

相关文章

网友评论

      本文标题:Objective C中target: action使用以及sw

      本文链接:https://www.haomeiwen.com/subject/ioumnttx.html