我有一个Notification观察器,它触发一个带有UIButton
类型参数的函数。
我一直在努力使通知工作,但由于某种原因我得到unrecognized selector sent to instance
以下是我的代码:
func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
let highlightedImage = UIImage(named: items[atIndex])
button.setImage(highlightedImage, for: .normal)
button.imageView?.contentMode = .scaleAspectFill
switch atIndex {
case 0:
button.tag = 0
NotificationCenter.default.addObserver(button, selector: #selector(handleEmotion), name: Notification.Name("sendnotif"), object: nil)
case 1:
print("Do something else")
default:
break
}
}
@objc func handleEmotion(_ note: Notification, sender: UIButton) {
if sender.tag == 0 {
sender.layer.borderColor = blueColor.cgColor
sender.layer.borderWidth = 2
}
}
我担心的是我应该如何使这段代码适用于case 0
以及随后的所有情况以及如何有效地将我的按钮传递给它。
我不认为使用通知是必要的。在不改变代码的情况下,一种方法是将addGestureRecognizer添加到按钮,并在创建按钮时使用各自的索引预先设置按钮的标记。
let button = UIButton()
button.tag = index
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleEmotion(_:))))
func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
let highlightedImage = UIImage(named: items[atIndex])
button.setImage(highlightedImage, for: .normal)
button.imageView?.contentMode = .scaleAspectFill
}
@objc func handleEmotion(_ sender: UIGestureRecognizer) {
if sender.view?.tag == 0 {
sender.layer.borderColor = blueColor.cgColor
sender.layer.borderWidth = 2
}
}
关于通知,在这种情况下,NotificationCenter.addObserver不应该放在那里。它应该只调用一次,所以可以把它放在viewDidLoad()中。然后在circleMenu函数中,点击按钮时应该做的是发布通知而不添加观察者。
NotificationCenter.default.addObserver(button, selector: #selector(handleEmotion), name: Notification.Name("sendnotif"), object: nil)
使用上面的行,您将按钮添加为目标,因此它期望在UIButton的实现中定义handleEmotion。因此你得到错误unrecognized selector sent to instance
如果您有权访问该按钮,则在发布通知时,您可以执行的操作。在viewWillAppear添加观察者
NotificationCenter.default.addObserver(self, selector: #selector(handleEmotion), name: Notification.Name("sendnotif"), object: nil)
然后将代码修改为
@objc func handleEmotion(note: Notification) {
if let userInfo = note.userInfo {
if let button = userInfo["button"] {
if button.view?.tag == 0 {
button.layer.borderColor = blueColor.cgColor
button.layer.borderWidth = 2
}
}
}
}
您可以在发布通知时使用以下内容
NotificationCenter.default.post(name: Notification.Name("sendnotif"), object: self, userInfo: ["button":button])