我正在 Swift
中以编程方式添加一个 UIButton
。
private let startBtn: UIButton = {
let btn = UIButton(type: .system)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Get Started!", for: .normal)
btn.backgroundColor = UIColor(red: 0, green: 1, blue: 1, alpha: 1.0)
btn.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 6
btn.layer.zPosition = 3
return btn
}()
一切正常,除了当我点击 UIButton
时,ratingButtonTapped()
没有被调用。
func ratingButtonTapped(_ button: UIButton) {
print("Button pressed")
}
当我将 translatesAutoresizingMaskIntoConstraints
更改为 true
时,调用 ratingButtonTapped()
。
view.translatesAutoresizingMaskIntoConstraints = true
但是 UIButton
没有出现在屏幕上。我认为这与 AutoLayout 有关(我不熟悉以编程方式添加元素)。我想继续使用 AutoLayout,因为我想避免使用视觉格式和框架。有什么办法可以做到这一点?
感谢您的宝贵时间。
最佳答案
1:检查您的 UIButton
是否未被其上方的另一个 UIView
覆盖,以防止触摸到达您的 UIButton
。
2:检查您的 UIButton
是否在它所添加到的 superView 的“外部”。例如,如果您将它放在 UIView
中,而 UIButton
在 UIView
rect
之外,那么触摸达不到。
当您无意中“错误”布局约束/框架时,可能会出现这些问题。
关于ios - translatesAutoresizingMaskIntoConstraints 阻止 UIButton Action swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444932/