ios - 作为 UIView 的 subview 的编程 UIButton 没有响应

标签 ios swift uibutton subview

我正在创建一个扩展 UITableViewCell 的类——它将显示一个社交媒体新闻源,每个单元格都是某人的帖子。

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

但是,UIButton 不响应点击,甚至不突出显示。它的superview本身有很多superview,都是栈,但是我查了一下,每个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
    

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

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

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

最佳答案

根据您显示的限制,您不能点击按钮,因为它在您的 superview 范围之外。

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

superview.clipsToBounds = true

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

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

例如,添加这些行:

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

关于ios - 作为 UIView 的 subview 的编程 UIButton 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59056955/

相关文章:

ios - MonoTouch 创建带圆角的 UIImage

iOS 9 如何以编程方式调用 "Back to"功能

ios - 为什么要这样使用 UIImagePickerController?

ios - UIButton:如何使用 imageEdgeInsets 和 titleEdgeInsets 使图像和文本居中?

ios - ScrollView 中的移动按钮 - iOS

ios - 应用程序中运行的计时器在一段时间后开始延迟触发,原因未知

ios - 如何列出所有使用 Graph API 3.x 版本的 friend ?

objective-c - 在 Obj-C 中使用 Swift 协议(protocol)的实现

swift - Finder "open with"应用 list

xcode - “再玩一次”按钮无法正常工作