如何在按钮的添加目标中传递参数



我有一个底部表单,在该表单上有一个按钮。我希望当我点击那个按钮时,它会转到与之相关的页面。我把它从storyboard连接到code

@IBOutlet weak var openPage: SheetOpenPageButton!

并为按钮编写扩展。

class SheetOpenPageButton: UIButton {
var navigationController: UINavigationController?
override var isSelected: Bool {
didSet {
if isSelected {
self.backgroundColor = UIColor(named: "CustomRed")
} else {
self.backgroundColor = UIColor(named: "CustomGray")
}
}
}

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

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

在collectionview中,当我点击按钮时,我调用这些方法。

let button = SheetOpenPageButton()
button.tag = cell.id ?? 1
button.addTarget(self, action: #selector(goToRestuarantFromStory(_ :)), for: .touchUpInside)
@objc func goToRestuarantFromStory(_ sender : UIButton) {
let restuarantVC = UIStoryboard(name: "Cafe", bundle: .main).instantiateViewController(withIdentifier: "RestuarantViewController") as! RestuarantViewController
restuarantVC.networkId = sender.tag
navigationController?.pushViewController(restuarantVC, animated: true)
print("smth")
removeSubview()
removeSubviewSpb()
vc.dismiss(animated: true, completion: nil)
}

这里我在addtarget使用按钮的标签传递参数。但是,当点击按钮时,它没有反应。我不知道如何解决这个问题。

SheetOpenPageButton不需要navigationController,在您这里展示的代码中既没有使用也没有实例化它。

你在goToRestuarantFromStory中引用的navigationcontroller [sic]是从你的collectionView的范围,根据你的代码也是nil,所以pushViewController从来没有实际调用。