UIStackView 中的按钮不可点击

Button in UIStackView not clickable

我正在尝试向我的堆栈视图添加一个按钮。该按钮有一个 buttonTapped 方法,当它被点击时应该被调用。问题是它永远不会被调用,按钮似乎不可点击。

class CustomButton: UIViewController {
    var buttonDelegate: ButtonDelegate?

    let button = UIButton(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width - 40, height: 30))
    
    init(label: String) {
        button.setTitle(label, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .systemBlue
        super.init(nibName: nil, bundle: nil)
    }
    
    @objc func buttonTapped() {
        print("this never gets printed")
        buttonDelegate?.buttonTapped(buttonType: .submit)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        view.addSubview(button)
    }
}

然后是我的主视图控制器:

protocol ButtonDelegate {
    func buttonTapped(buttonType: ButtonType)
}

class DynamicViewController: UIViewController, ButtonDelegate {
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()

    lazy var stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        return stackView
    }()


    lazy var contentView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    private func setupViews() {
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(stackView)
        
        let btn = CustomButton(label: "hi")
        btn.buttonDelegate = self
        self.stackView.addArrangedSubview(btn.view)
    }

    func buttonTapped(buttonType: ButtonType) {
        print("also never gets printed")
    }
}

没有任何东西与按钮重叠或类似的东西:

我的问题是为什么按钮不可点击。

您正在将视图控制器添加为子视图。所以你还需要添加为child。 在self.stackView.addArrangedSubview(btn.view)这一行之后添加下面的代码。

self.addChild(btn)
btn.didMove(toParent: self)