自定义UIButton - IBAction无效

时间:2017-08-17 00:30:18

标签: ios swift uibutton

我有一个默认的UIButton链接到IBAction(内部修饰)。这很好用,所以我知道我的连接没问题。一旦我将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
    }
}

2 个答案:

答案 0 :(得分:2)

您的代码无效,因为按钮不再接收触摸。所有触摸都会发送到您添加的最顶层自定义视图。

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

答案 1 :(得分:0)

您添加的视图涵盖了您的自定义按钮。