Target-Action

来源:互联网 发布:娶俄罗斯女人知乎 编辑:程序博客网 时间:2024/05/14 16:32
#import <UIKit/UIKit.h>@interface MyButton : UIView// 1.写一个自定义的方法- (void)addNewTarget:(id)target action:(SEL)action;//  SEl 方法选择器// 2.写两条属性,分别保存传过来的执行方法和委托人@property(nonatomic, assign) id target;@property(nonatomic, assign) SEL action;@end
#import "MyButton.h"@implementation MyButton- (void)addNewTarget:(id)target action:(SEL)action { // 第三步:通过属性保存传过来的委托者和需要执行的方法   self.target = target;   self.action = action; }// 第四步:给MYView一个触发的条件- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event    {    NSLog(@"%@", [self.target class]);    NSLog(@"%@", self.action);    NSLog(@"%@", self.class);    // 第五部:myView去调用执行委托人的方法    [self.target performSelector:self.action withObject:self];   }@end
#import "RootViewController.h"#import "MyButton.h"@interface RootViewController ()@end@implementation RootViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    self.view.backgroundColor = [UIColor whiteColor];    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];    button.frame = CGRectMake(100, 100, 150, 50);    button.layer.borderWidth = 1;    button.layer.cornerRadius = 10;    // 给边框加颜色    button.layer.borderColor = [UIColor redColor].CGColor;    [self.view addSubview:button];     [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpOutside]; // 创建MyButton    MyButton *myButton = [[MyButton alloc] initWithFrame:CGRectMake(100, 200, 150, 50)];    myButton.backgroundColor = [UIColor cyanColor];    [self.view addSubview:myButton];    [myButton release];// 6.mybutton对象调用自定义的方法[myButton addNewTarget:self action:@selector(test)];}- (void)test {   NSLog (@"测试");  }
0 0
原创粉丝点击