“高内聚,低耦合”是面向对象编程的核心思想.
使用 target…action 实现解耦.
需要目标去执行一个动作的地方.
例如, 定义一个继承于UIView 的MyButton 类, 让他能够有Button的点击方法.
代码如下:
Mybutton.h:
#import <UIKit/UIKit.h>
@interface Mybutton : UIView
//1.写一个自定义方法,把目标和对应动作传过来.
- (void)addNewTarget:(id)target Action:(SEL)action;
//2.定义两条属性.
@property(nonatomic, assign)id target;
@property(nonatomic, assign)SEL action;
@end
Mybutton.m:
#import "Mybutton.h"
@implementation Mybutton
- (void)addNewTarget:(id)target Action:(SEL)action{
// 目标动作保存到属性中.
self.target = target;
self.action = action;
}
//4.给他一个触发的条件.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.target performSelector:self.action withObject:self];
}
@end
回到根视图的.m文件,代码如下:
#import "MainViewController.h"
#import "Mybutton.h"
@interface MainViewController ()
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 通过UIView来模拟一个Button的点击事件.
Mybutton *View_button = [[Mybutton alloc] initWithFrame:CGRectMake(100, 100, 150, 100)];
View_button.backgroundColor = [UIColor orangeColor];
[self.view addSubview:View_button];
[View_button release];
//6.使用自定义方法
[View_button addNewTarget:self Action:@selector(click:)];
}
- (void)click:(Mybutton *)button{
// 检测是否成功.
NSLog(@"成功!");
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-25 08:05:33