博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Button加在UITableViewHeaderFooterView的self.contentView上导致不能响应点击
阅读量:4544 次
发布时间:2019-06-08

本文共 2033 字,大约阅读时间需要 6 分钟。

你有没有遇到过Button加在UITableViewHeaderFooterView的self.contentView上导致不能响应点击的情况,下面记录一下我遇到的原因和解决方法:

代码如下:

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {                self.titleLabel = [[UILabel alloc]init];        self.titleLabel.textColor = [UIColor redColor];        self.titleLabel.font = [UIFont systemFontOfSize:16];        [self.contentView addSubview:self.titleLabel];         self.titleLabel.frame = CGRectMake(10, 15, 50, 20);

         self.cleckBtn = [UIButton buttonWithType:UIButtonTypeCustom];

[self.cleckBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];        self.cleckBtn.titleLabel.font = [UIFont systemFontOfSize:14];        [self.cleckBtn    addTarget:self action:@selector(cleckTouchBtn:) forControlEvents:UIControlEventTouchUpInside];        [self.contentView addSubview:self.cleckBtn];    }    return self;}- (void)cleckTouchBtn:(UIButton *)button{        if (self.block) {        self.block(self.titleLabel.text,self.cleckBtn);    }}-(void)layoutSubviews{        self.cleckBtn.frame = CGRectMake(100 , 10, 100 , 30);}

分析:

UIButton不能响应点击事件的原因大概有以下三种:

1. UIButton的userInteractionEnabled默认YES,如果设置NO,UIButton就不会有响应点击事件,同时如果 UIButton的父视图的userInteractionEnabled属性为NO,UIButton也会受到影响,不会有响应。

从UIButton的父视图和UIButton的userInteractionEnabled统统设置YES,这个问题仍然无法解决,所以不是这个问题。

2. 另外就是button本身的frame问题,或者有没有一层视图盖住了button导致按钮无响应,简单来说就是按钮本身和按钮他爹(父视图)的问题。

3. UIButton不能响应点击事件的另一个原因是和UIButton的父视图有关系。如果父视图frame是CGRectZero,或者UIButton超出父视图,UIButton还是会显示的,但诡异的是UIButton是不会响应点击事件的,所以要调整父视图的frame或者UIButton位置。

依次排除...

最后发现,原因如下:

-(void)layoutSubviews{

 

self.cleckBtn.frame = CGRectMake(100 , 10, 100 , 30);

}

在该方法中,我没有调用父类方法,意味着放弃了里面其他子视图的布局,只布局这一个按钮.导致frame造成不能点击响应.

 

解决方法:

1>方法一:

-(void)layoutSubviews{	    [super layoutSubviews];    self.titleLabel.frame = CGRectMake(10, 15, 50, 20);	self.cleckBtn.frame = CGRectMake(100 , 10, 100 , 30);}

2>方法二:

直接把子控件加在self上就可以了,不需要加载self.contentView也是可以的.

 

转载于:https://www.cnblogs.com/pengsi/p/6862557.html

你可能感兴趣的文章
IOS7 position:fixed 定位问题
查看>>
12.伪类选择器与伪元素的应用
查看>>
Oracle存储过程基本语法
查看>>
JS高程第八章 BOM
查看>>
python-vi
查看>>
Unix进程控制
查看>>
DNS解析过程详解
查看>>
51Nod 1181 质数中的质数(质数筛法)
查看>>
并发编程学习总结
查看>>
Xamarin.Android 上中下布局
查看>>
VS Code使用记录
查看>>
locust参数化(数据库取值)
查看>>
Google Protocol Buffers浅析(三)
查看>>
.net core 中使用Google的protoc
查看>>
Spring Cloud和Spring Boot的区别
查看>>
jquery实现图片上传前本地预览
查看>>
C# — 题库答案汇总
查看>>
docker居然需要3.10以上的内核
查看>>
Win10下安装zookeeper
查看>>
客户端用JavaScript填充DropDownList控件,服务器端读不到值
查看>>