UIday05_zy01:target/action 设计模式

target/action 设计模式

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    RootViewController * rootVC = [[RootViewController alloc]init];
    self.window.rootViewController = rootVC;
    
    return YES;
}

RootViewController.m

@interface RootViewController ()

@property(nonatomic,strong)RootView * rv;

@end

@implementation RootViewController

-(void)loadView{
    self.rv = [[RootView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.view = _rv;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 添加点击事件
    [self.rv.myButton myAddtarget:self action:@selector(myButtonAction:)];
    
}

-(void)myButtonAction:(MyButtonView *)sender{
    NSLog(@"targetAction");
}

@end 

RootView.h

#import <UIKit/UIKit.h>
#import "MyButtonView.h"

@interface RootView : UIView

@property(nonatomic,strong)MyButtonView * myButton;


@end

RootView.m

#import "RootView.h"

@implementation RootView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor yellowColor];
        
        self.myButton = [[MyButtonView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
        
        self.myButton.backgroundColor = [UIColor blueColor];
        
        [self addSubview:_myButton];
        
    }
    return self;
}

@end

MyButtonView.h

#import <UIKit/UIKit.h>

@interface MyButtonView : UIView{
    
    // 两个实例变量
    // 谁执行方法
    id _target;
    // 执行什么方法
    SEL _action;
    
}

// 方法:给两个实例变量赋值
-(void)myAddtarget:(id)target action:(SEL)action;

@end

MyButtonView.m

#import "MyButtonView.h"

@implementation MyButtonView

// 方法给两个实例变量赋值
-(void)myAddtarget:(id)target action:(SEL)action{
    _target = target;
    _action = action;
}


// 重写touchBegan
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_target performSelector:_action withObject:self ];
}

@end





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值