IOS自定义View使用block实现点击事件

一般自定义view的点击事件触发都会经过touchevent事件。

事件处理只需要重写这个这些方法就好。

比如重写

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
这个方法

而一般在viewcontroller里使用view的点击事件的时候,都会使用delegate的方式来处理。

今天主要结束下。利用block来处理简单的view的事件处理。

新建一个view继承 UIView ,声明一个block,并创建一个初始化方法。初始化方法传入点击事件的block。
.h文件
@interface moreView: UIView
{
    void (^moreViewClick)();//声明一个block
}
- (id)initWithFrame:(CGRect)frame :( void (^) () ) moreclick;

在.m文件中实现初始化方法,并在touchevent方法中使用block
.m文件代码
- (id)initWithFrame:(CGRect)frame :( void (^) () ) moreclick{

    self = [super initWithFrame:frame];

    //给view里的block赋值
    moreViewClick = moreclick;

    

    if (self) {
        // Initialization code=

        处理自己的逻辑

    }
    return self;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    NSLog(@"more点击结束");
    //在此处使用点击block
    moreViewClick();
}

在viewcontroller里使用
创建的时候直接初始化出block即可。
moreView *more = [[moreView alloc] initWithFrame:CGRectMake(0, 0, AppWidth-10, 30) :^{
    NSLog(@"more点击结束");
    CategoryListView *cv = [[CategoryListView alloc] init];
    [self.navigationController pushViewController:cv animated:YES];

}];

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值