UIKit之target/action设计模式  delegate

target/action

  • 耦合 是衡量一个程序好坏的标准之一(表示代码块之间的关联度,就和写作文的段落关联类似)
  • MVC设计模式 就可以降低代码的耦合度
  • 好代码的耦合度一定是非常低的
  • "高内聚 低耦合"是面向对象编程的核心思想

view.h文件中

// target-action
// view的两个属性
@property(nonatomic,assign)id target;
@property(nonatomic,assign)SEL action;

// 方法
- (void)myAddTarget:(id)target action:(SEL)action;

view.m文件中

- (void)myAddTarget:(id)target action:(SEL)action{
   self.target= target;
   self.action= action;
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
   // performSelecter方法
    [self.target performSelector:self.action withObject:self];
}

Controller.m文件中

#define A arc4random()%255/255.0

@interface RootViewController()
@property(nonatomic,retain)RootView*rootV;
@end

@implementationRootViewController
// 耦合 是衡量一个程序好坏的标准之一(表示代码块之间的关联度,就和写作文的段落关联类似)

// MVC设计模式 就可以降低代码的耦合度

// 好代码的耦合度一定是非常低的

// "高内聚 低耦合"是面向对象编程的核心思想

- (void)loadView{
   self.rootV= [[RootView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
   self.view=self.rootV;
}
- (void)viewDidLoad {
    [superviewDidLoad];    
    [self.rootV.colorButton colortarget:selfaction:@selector(changeColor:)];
   // Do any additional setup after loading the view.
}
- (void)changeColor:(UIView*)sender{
    sender.backgroundColor= [UIColor colorWithRed:Agreen:Ablue:Aalpha:1];
}

delegate协议

// 1. 设置协议
@protocol ColorDelegate 
// 2. 协议的方法
- (void)colorView:(UIView*)aView;
@end
@interfaceColorView :UIView
// 3.设置协议属性,(可以设置代理人)
@property(nonatomic,retain)id<ColorDelegate>colordelegate;
@end

// 4.设置点击(触摸)时,要干的事情(设置谁是代理者)
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
    [self.colordelegate colorView:self];
}
@end

RootView.h中

// 5.设置制定协议的view的 贴在那个view上面
@property(nonatomic,retain)ColorView*colorView;
RootView.m中
 // 6. 初始化设置view的位置
 self.colorView= [[ColorView alloc]initWithFrame:CGRectMake(200, 200, 100, 100)];
   [self addSubview:self.colorView];
// 7. 代理遵循协议
@interface RootViewController()<ClickViewDelegate,ColorDelegate>
 // 8.设置遵循协议的代理
    self.rootV.colorView.colordelegate=self;
}
- (void)clickView:(UIView*)aView{
   NSLog(@"abc");
}
// 9. 代理实现协议里的方法
- (void)colorView:(UIView*)aView{
    aView.backgroundColor= [UIColorcolorWithRed:Agreen:Ablue:Aalpha:1];
   NSLog(@"123");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,830评论 25 709
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,221评论 30 472
  • 安装nginx yum install nginx -y 注:修改/etc/nginx/conf.d/defaul...
    嘚嘚嘚的少年阅读 351评论 1 0
  • 准备明细 那么按照项目管理的思路,(领导/组织/用人/计划/控制)我们可以把婚礼准备活动拆分成三大块: 组织建设婚...
    百木子阅读 1,330评论 0 5