ios - 无法点击自定义按钮 Swift

标签 ios swift uibutton

我已经用代码创建了 5 个自定义按钮,它们都完美地显示出来;但是,由于某种原因,当它们处于非事件状态时被点击时没有任何响应。我已经在我的 ViewDidLoad 中添加了 subview ,并将约束编码在一个不重要的单独函数中,我不相信这一点所以让我知道是否需要更好地理解。

代码:

let backgroundImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true

return imageView
}()

let transparentView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black
view.backgroundColor = view.backgroundColor?.withAlphaComponent(0.5)

return view
}()


let button1: UIButton = {
let button = UIButton(type: .custom)
button.addTarget(self, action: #selector(button1Pressed), for: .touchUpInside)
button.setImage(UIImage(named: "button"), for: .normal)
button.isUserInteractionEnabled = true


return button
}()


override func viewDidLoad() {
super.viewDidLoad()

addSubviews()

setupViewConstraints()

}

func addSubviews() {
self.view.addSubview(backgroundImageView)
backgroundImageView.addSubview(transparentView)
transparentView.addSubview(button1)
}

func setupViewConstraints() {

backgroundImageView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

transparentView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

 button1.anchor(top: nil, left: nil, bottom: view.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 20, paddingRight: 0, width: 80, height: 80)
  button1.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

}

@objc func button1Pressed() {
print("Button1 pressed")
}

最佳答案

默认情况下,用户交互在 UIImageView 实例中被禁用。当父 View 的用户交互被禁用时,其 subview 无法接收用户交互,即使您已设置 button.isUserInteractionEnabled = true

所以在backgroundImageView闭包中添加imageView.isUserInteractionEnabled = true

let backgroundImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.isUserInteractionEnabled = true
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.layer.masksToBounds = true
    return imageView
}()

关于ios - 无法点击自定义按钮 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248876/

相关文章:

ios - 如何在缩放后校准 Sprite 触摸位置

objective-c - 如何将图像设置为 UIImage

iOS SWIFT - CollectionView 特定单元格通过触摸扩展

swift - 'Use of self in method call before super.init initializes self',无法通过方法调用初始化属性

iphone - 管理多个按下的 UIButton

ios - 以编程方式设置 RoundedRect 按钮

ios - 通过本地 URL 从图库加载图像(Swift)

ios - 如何扫描我所在地区 iOS 中的可用信标

ios - Array.contains 返回 false

ios - 代码在模拟器上运行良好,但在真实设备上却为零