ios - 自定义 UIButton - IBAction 不工作

标签 ios swift uibutton

我有一个链接到 IBAction 的默认 UIButton(在内部进行修饰)。这工作正常,所以我知道我的连接没问题。一旦我将 UIButton 类更改为我的自定义按钮,就不再触发 IBAction。下面是我的自定义 UIButton 的代码。知道为什么会这样吗?

import UIKit

@IBDesignable
class PrimaryButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initView()
    }


    private func initView() {
        let view = viewFromNibForClass()

        view.frame = bounds

        view.autoresizingMask = [
            UIViewAutoresizing.flexibleWidth,
            UIViewAutoresizing.flexibleHeight
        ]

        addSubview(view)
    }

    private func viewFromNibForClass() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view
    }
}

最佳答案

您的代码不起作用,因为按钮不再接收触摸。所有触摸都会发送到您添加的最顶层的自定义 View 。

设置 view.userInteractionEnabled = false 使其对触摸透明。

关于ios - 自定义 UIButton - IBAction 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724888/

相关文章:

swift - 如何在 Swift 中将 NSUserDefault 与 PickerView 一起使用?

ios - 手动更新 SwiftUI View

iphone - UIButton 事件 'Touch Up Inside' 不起作用。 'Touch Down' 工作正常

ios - titleLabel 无法在 UIButton 中正确适应高度

ios - 如何从 ActionSheet 更改 UIButton 的文本

ios - Xcode 4.3.3 编译项目 -> 构建成功,但 Phonegap-App 无法安装在 iPhone 3G 上

ios - 使用 Swift 中更新的 header Transmission 重新发送您的请求

ios - 用户进入特定区域时如何获取本地通知提供的 ios

ios - 如何在 swift 4 中重新排序单元格后保存 tableView 顺序

ios - Xcode 9.1无法启动Iphone模拟器