• UIButton无法响应点击事件


    一、问题描述

    因为项目需要,需要UITableView上添加固定的筛选表头,一直固定,不能随UITableView滚动。所以直接将表头与UITableView分离,将它添加到控制器的UIView上,即添加到UITableView的父视图上,与UITableView同级。然后表头上添加三个UIButton,效果达到预期,但问题随即出现。筛选表头上的UIButton无法响应点击事件,刚开始以为造成的原因是手误把UIButton的父视图或者UIButton属性userInteractionEnabled被设置为NO,试着UIButton的父视图和UIButton的userInteractionEnabled统统设置YES,仍然无法解决这个问题。

    二、问题分析

    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位置。

    第一种:试过了,排除。

    第二种:因为用到MBProgressHUD,所以第二种有可能。但经过调试,发现MBProgressHUD是隐藏的,不会遮挡点击事件,同时假设MBProgressHUD不隐藏,应该同级的UITableView也不能点击,但UITableView能响应点击事件,所以第二种也排除。

    第三种:但先设置UIButton的父视图背景色为红色,同时先把UIButton都去掉,调试发现UIView并没有显示出来。打印UIView的frame,值为{{0, 0}, {414, 44}}。原来问题出现在这里。为什么不能显示?

    原来我设置了frame,还用Masonry设置约束。设置了约束,frame是无效的,同时因为约束设置不合理,导致UIView无法显示。

        [self.filerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top);
        }];

    三、问题解决

    UIView的frame去掉,同时设置一个高度约束。

        [self.filerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(strongSelf.view.mas_left);
            make.right.equalTo(strongSelf.view.mas_right);
            make.top.equalTo(strongSelf.view.mas_top);
            make.height.equalTo(@44);
        }];    

    效果如下:

    然后加上UIButton,UIButton能响应点击事件

    学习,以记之。如有错漏,欢迎指正

    作者:冯子武
    出处:http://www.cnblogs.com/Zev_Fung/
    本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
    如果博文对您有所收获,请点击下方的 [推荐],谢谢

  • 相关阅读:
    NERDTree 快捷件
    atom安装插件
    flask/sqlalchemy
    python中SQL的使用
    vim配置
    Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights
    address-already in use 以及查看端口
    github桌面工具commit不了解决
    git add 所有文件
    Beta 冲刺(5/7)
  • 原文地址:https://www.cnblogs.com/Zev_Fung/p/5794203.html
Copyright © 2020-2023  润新知