vickate _触摸事件处理 实现UIView替代UIButton

本文详细介绍如何在iOS应用中通过自定义TouchView类来模拟UIButton的点击效果,并利用手势响应实现视图背景颜色变化及大小调整等功能。文章还介绍了如何通过代理模式扩展TouchView的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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的博客,谢谢!大笑大笑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值