關(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!!!"
}