1. 设置根视图控制器
RootViewController *rootVC = [[RootViewController alloc] init];
self.window.rootViewController = rootVC;
[rootVC release];
2. 创建TouchView类 然后在.m文件中实现
// 传递两个参数
{
id _target; // 记录谁被点了
SEL _action; // 点完后执行什么?
}
// 声明一个方法模仿button添加点击事件
- (void)addTarget:(id)targrt action:(SEL)action;
// 实现方法
- (void)addTarget:(id)targrt action:(SEL)action
{
// 进行赋值
_target = targrt;
_action = action;
}
// 处理事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_target performSelector:_action withObject:self]; // 给这个对象 发送一个消息 withObject:可以携带参数
}
3. 使用UIView模拟button的点击方法
<span style="font-size:18px;"> TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
touchView.backgroundColor = [UIColor grayColor];
[touchView addTarget:self action:@selector(actionTouchView:)];
[self.view addSubview:touchView];
[touchView release];</span>
4. 触摸实现点击方法
// 实现点击方法!
- (void)actionTouchView:(id)view
{
// 如果使用id类型 需要转换一下类型
TouchView *touchView = view;
touchView.backgroundColor = [UIColor purpleColor];
}
5.可以为touchView添加一个代理,实现一些其他功能
// 创建一个协议
@protocol DelegateViewDelegate <NSObject>
// 填写方法
// 改变大小
- (void)changeSizeWithView:(DelegateView *)view;
// 随机改变颜色
- (void)changeColorWithView:(DelegateView *)view;
@end
// 声明一个代理属性
@property (nonatomic, assign)id<DelegateViewDelegate> delegate;
// 遵循协议 实现方法 设置代理
@interface RootViewController : UIViewController<DelegateViewDelegate>
DelegateView *delegateView = [[DelegateView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
delegateView.delegate = self;
delegateView.backgroundColor = [UIColor purpleColor];
[self.view addSubview:delegateView];
// 实现协议中的方法
- (void)changeSizeWithView:(DelegateView *)view
{
// 更改点击过后的大小
view.frame = CGRectMake(100, 100, 200, 200);
}
// 实现改变颜色的协议方法
- (void)changeColorWithView:(DelegateView *)view
{
// 触摸随机更改颜色
view.backgroundColor = [UIColor colorWithRed:arc4random() % 256/ 255.0 green:arc4random() % 256/ 255.0 blue:arc4random() % 256/ 255.0 alpha:1];
}
// 让代理去干活
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 更改大小
[_delegate changeSizeWithView:self];
// 随机改变颜色
[_delegate changeColorWithView:self];
}
欢迎光顾iOS_Bay的博客,谢谢!