UIButton 不响应点击

UIButton not responding to tap

UIButton 操作在我点击时不起作用。我在 Stack Overflow 上尝试了另一个 post 的其他建议,但没有任何效果。下面是我的代码:

    let saveBtn = GActionBtn(type: .system)

    lazy var footer: UIView = {
        let v = UIView()
        v.isUserInteractionEnabled = true
        v.addSubview(saveBtn)
        saveBtn.isUserInteractionEnabled = true
        saveBtn.addTarget(self, action: #selector(handleSave), for: .touchUpInside)
        saveBtn.backgroundColor = #colorLiteral(red: 0.4470588235, green: 0.6274509804, blue: 0.3960784314, alpha: 1)
        saveBtn.layer.cornerRadius = 27.5
        let attributeString = NSAttributedString(string: "Save".localized(), attributes: [NSAttributedString.Key.font: UIFont(name: "NunitoSans-Bold", size: 16), NSAttributedString.Key.foregroundColor: UIColor.white])
        saveBtn.setAttributedTitle(attributeString, for: .normal)
        NSLayoutConstraint.activate([
            saveBtn.centerXAnchor.constraint(equalTo: v.centerXAnchor),
            saveBtn.centerYAnchor.constraint(equalTo: v.centerYAnchor, constant: 54),
            saveBtn.widthAnchor.constraint(equalToConstant: 312),
            saveBtn.heightAnchor.constraint(equalToConstant: 52)
        ])
        return v
    }()

    @objc private func handleSave() {
        print("save")
    }

    private func setupTableView() {
        tableView = UITableView(frame: .zero, style: .grouped)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
        tableView.separatorStyle = .none
        tableView.keyboardDismissMode = .interactive
        tableView.backgroundColor = .white
        tableView.tableFooterView = footer
    }

@ferryawijayanto 根据 Sh_Khan 建议,是的,你应该 return UIButton 直接到 tableFooterView。它会接受它。像下面这样尝试,

 private func setupTableView() {
    tableView = UITableView(frame: .zero, style: .grouped)
    tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 80, right: 0)
    tableView.separatorStyle = .none
    tableView.keyboardDismissMode = .interactive
    tableView.backgroundColor = .white

    let saveBtn = UIButton (type: .system)
    saveBtn.isUserInteractionEnabled = true
    saveBtn.addTarget(self, action: #selector(handleSave), for: .touchUpInside)
    saveBtn.backgroundColor = #colorLiteral(red: 0.4470588235, green: 0.6274509804, blue: 0.3960784314, alpha: 1)
    saveBtn.layer.cornerRadius = 27.5
    let attributeString = NSAttributedString(string: "Save".localized(), attributes: [NSAttributedString.Key.font: UIFont(name: "NunitoSans-Bold", size: 16), NSAttributedString.Key.foregroundColor: UIColor.white])
    saveBtn.setAttributedTitle(attributeString, for: .normal)


    tableView.tableFooterView = saveBtn
}

如果你想要完整的宽度和高度,定义 heightForFooterSection 意味着 UIButton 会自动从页脚框架更新它的框架。否则你想自定义静态宽度和高度,你可以不受限制地使用框架。当然你也应该尝试使用约束。

我希望它能帮助您实现所需的输出。