Button加在UITableViewHeaderFooterView的self.contentView上导致不能响应点击

你有没有遇到过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