我在设置按钮目标时出现错误unrecognized selector sent to instance
。我在Xib文件中定义了按钮(有点警报),当按下此按钮时它将定位到ViewController函数。如何在xib按钮上调用函数?
Xib代码
@IBDesignable class DeleteAlert: UIView {
@IBOutlet weak var myBtn: UIButton!
let VC = ViewController()
override func awakeFromNib() {
super.awakeFromNib()
layoutIfNeeded()
myBtn.addTarget(self, action: #selector(VC.deleteImage(_:)), for: .touchUpInside)
}
@IBAction func didCancel(_ sender: Any) {
removeFromSuperview()
}
@IBAction func didDelete(_ sender: Any) {
}
}
ViewController函数
@objc func deleteImage(_ sender: AnyObject){
let row = sender.view.tag
self.data?.remove(at: row)
self.images?.remove(at: row)
self.collectionView.reloadData()
}
在这里,您需要使用自定义委托来访问按钮操作。试试这个
protocol handleDeleteAction {
func didDeleteButtonClicked(UIButton)
}
@IBDesignable class DeleteAlert: UIView {
@IBOutlet weak var myBtn: UIButton!
// Now create a variable in DeleteAlert view
var delegate: handleDeleteAction?
override func awakeFromNib() {
super.awakeFromNib()
layoutIfNeeded()
myBtn.addTarget(self, action: #selector(didDelete(_:)), for: .touchUpInside)
}
@IBAction func didCancel(_ sender: Any) {
removeFromSuperview()
}
@IBAction func didDelete(_ sender: Any) {
self.delegate?.didDeleteButtonClicked(sender:sender)
}
}
在您的viewcontroller viewdidload中调用委托
let deleteAlertView : DeleteAlert !
deleteAlertView.delegate = self
并像这样处理动作,然后您的viewController确认为协议
extension ViewController : handleDeleteAction {
func didDeleteButtonClicked(sender:UIButton) {
let row = sender.view.tag
self.data?.remove(at: row)
self.images?.remove(at: row)
self.collectionView.reloadData()
}
}