UI基础-设计模式、手势识别器

target/action设计模式

耦合

耦合是衡量一个程序写的好坏的标准之一,
耦合是衡量模块与模块之间关联程度的指标
“高内聚,低耦合”是面向对象编程的核心思想。

使用target…action实现解耦

例如:点击imageView实现换背景颜色 并且遵循MVC设计模式
1.准备工作:新建工程,新建一个视图控制器,将其设置为根视图控制器
2.新建一个ButtonView继承于UIView
3.在ButtonView.h中声明两个属性(记得dealloc)

@property (nonatomic, retain) id target;
@property (nonatomic, assign) SEL action;

4.重写初始化方法

- (instancetype)initWithFrame:(CGRect)frame target:(id)target action:(SEL)action
{
self = [super initWithFrame:frame];
if (self) {
    // 初始化时 对属性 进行赋值
    self.target = target;
    self.action = action;
}
return self;
}

5.添加触摸方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"开始触摸");
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"取消触摸");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"点击");
// 使用self.target对象调用 action方法
// 让一个对象 去调用这个对象类里的方法
//  Object 可携带的参数
[self.target performSelector:self.action withObject:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
}

6.在根视图控制器的viewDidLoad中,创建ButtonView的对象

ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(100, 100, 200, 200) target:self action:@selector(buttonViewClick:)];
buttonView.backgroundColor = [UIColor redColor];
[self.view addSubview:buttonView];
[buttonView release];

7.实现方法

- (void)buttonViewClick:(ButtonView *)buttonView
{
// 改变背景颜色
butt
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值