target/action 设计模式

#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate
-(void)dealloc{
    [_window release];
    [super dealloc];
}

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



#import "RootViewController.h"
#import "TapView.h"
@interface RootViewController ()
@property (nonatomic,retain)TapView * tapView;
@end

@implementation RootViewController
-(void)dealloc{
    [_tapView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _tapView = [[TapView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    _tapView.backgroundColor = [UIColor yellowColor];
//    _tapView.target = self;
//    _tapView.action = @selector(changerColor);
    //调用自定义方法
    [_tapView myTarget:self andAction:@selector(click)];
    [self.view addSubview:_tapView];
    [_tapView release];
}

-(void)changerColor{
    UIColor * color = [UIColor colorWithRed:242/255.0 green:168/255.0 blue:203/255.0 alpha:0.5];
    _tapView.backgroundColor = color;
}
-(void)click{
    NSLog(@"猴赛雷");
}

#import "TapView.h"

@implementation TapView


//触摸开始方法,(模仿按钮添加事件方法)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //当视图被点击的时候,让target区执行_action的方法操作,并且将自己传过去
    if (_target != nil && [[_target class]instancesRespondToSelector:_action]) {
        [_target performSelector:_action withObject:self];
    }
}
//自定义方法
-(void)myTarget:(id)target andAction:(SEL)action{
    _target = target;
    _action = action;
    
}


#import <UIKit/UIKit.h>

@interface TapView : UIView
//sel就是@seleact
@property (nonatomic,assign)id target;//目标
@property (nonatomic,assign)SEL action;//事件行为
//自定义一个方法
-(void)myTarget:(id)target andAction:(SEL)action;


@end

博主新博客地址Swift学习笔记: 点击打开链接

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值