美文网首页
UIKit之target/action设计模式  delegat

UIKit之target/action设计模式  delegat

作者: MI移动 | 来源:发表于2017-07-20 10:12 被阅读0次

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");
}

相关文章

网友评论

      本文标题:UIKit之target/action设计模式  delegat

      本文链接:https://www.haomeiwen.com/subject/ndrdkxtx.html