作为 UIView 的子视图的编程 UIButton 没有响应

Programmatic UIButton as a subview of UIView is not responding

我正在制作一个扩展 UITableViewCell 的 class——它将显示社交媒体新闻源,每个单元格都是某人的 post。

我添加了一个 UIButton 作为 UIView 的子视图,因此 UIView 将同时包含按钮和标签作为子视图,like this。 (抱歉,图片有点小,但我想你会明白的)。

但是,UIButton 不响应点击,甚至不突出显示。它的superview本身有多个superview,都是stack,但是我查了一下,每个superview的isUserInteractionEnabled都是true。

    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button(UIImage(named: "vertical_dots")?.withRenderingMode(.alwaysOriginal), for: .normal)
    button.backgroundColor = .white
    button.imageView?.contentMode = .scaleAspectFit
    button.addTarget(self, action: #selector(myButtonAction), for: .touchUpInside)
    
    label.text = "\(userPost?.minutesAgo)m"
    label.font = label.font.withSize(11.0)
    label.textColor = .lightGray
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 1
    
    let superview = UIView()
    superview.translatesAutoresizingMaskIntoConstraints = false
    superview.addSubview(button)
    superview.addSubview(label)
    
    label.leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
    label.heightAnchor.constraint(equalToConstant: 40).isActive = true
    label.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
    button.leftAnchor.constraint(equalTo: label.rightAnchor).isActive = true
    button.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
    button.heightAnchor.constraint(equalToConstant: 20).isActive = true
    button.widthAnchor.constraint(equalToConstant: 15).isActive = true
    

我收到很多约束警告,但我认为这不会影响事情?

请注意,这只是我的一部分代码,我正在将超级视图添加到其他视图,但我不会在这里展示所有内容。 None 我的观点有框架,只有约束,而且它们都正确显示。

我认为以前没有人问过这个问题,因为其他人正在使用 Interface Builder,而我是以编程方式完成的。

可能是 table 视图单元格认为它被选中并正在取消按钮的触摸。

试试这个:

tableView.allowsSelection = false

如果不是这种情况,请尝试检查按钮的框架,看看您是否真的在点击它。您可以use the Debug View Hierarchy button检查一下。

另外,你可以试试:

button.clipSubviews = true

如果你看不到你的按钮,那么框架是错误的,你不能点击按钮框架之外的地方。 (即使你能看到它。)

根据您显示的限制,您不能点击按钮,因为它超出了您的 superview

要确认这一点,请添加此行:

superview.clipsToBounds = true

而且您几乎肯定不会看到您的按钮或标签。

您需要给出 superview 宽度和高度约束,或者您需要添加约束以便子视图确定父视图的边界。

例如,添加这些行:

    label.topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
    label.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
    button.rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true