自定义按钮无法点击 Swift

Posted

技术标签:

【中文标题】自定义按钮无法点击 Swift【英文标题】:Custom buttons can't be tapped Swift 【发布时间】:2019-07-29 07:19:42 【问题描述】:

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

代码:

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")

【问题讨论】:

尝试在viewDidLoad中添加目标 可以添加setupViewConstraints()的代码吗? @Azat 我试过了,可惜没用 @AlexandrKolesnik 我刚刚更新了代码并添加了 setupViewConstraints() 【参考方案1】:

默认情况下,UIImageView 实例中禁用用户交互。并且当一个superview的用户交互被禁用时,它的子视图不能接收用户交互,即使你设置了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
()

【讨论】:

以上是关于自定义按钮无法点击 Swift的主要内容,如果未能解决你的问题,请参考以下文章

Swift在按钮点击上添加自定义单元格

Swift - 如何在自定义 AlertController 中点击按钮时呈现 ViewController

FacebookSDK(4.1.x) 自定义登录 UI 按钮 - Swift(1.2)

创建自定义按钮形状 Swift 4

UITableViewCell 自定义按钮图像未在 Swift 3 中更新

swift UIViewController用于自定义单元格中的按钮