ios - translatesAutoresizingMaskIntoConstraints 阻止 UIButton Action swift

标签 ios swift uibutton autolayout

我正在 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 中,而 UIButtonUIView rect 之外,那么触摸达不到。

当您无意中“错误”布局约束/框架时,可能会出现这些问题。

关于ios - translatesAutoresizingMaskIntoConstraints 阻止 UIButton Action swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444932/

相关文章:

ios - curl 和 URLSession 返回不同的数据

ios - ios,当按钮更改为选定状态时,如何更改图像和隐藏标题?

iphone - AVCaptureSession 暂停和恢复记录

ios - OpenGL 中的离屏帧缓冲区

iOS 解析 Stripe 集成

ios - 当键盘从堆栈溢出中出现时无法获得任何滚动 TextView 的响应

swift - 如何(正确)使用 cocoa 安全框架

iphone - 录音机中的音频表

iphone - UIButton setTitle forState 不起作用

xcode - 按钮重叠背景图片点击问题