将参数 UI 按钮添加到通知中心观察器



我有一个通知观察器,它触发了一个采用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,随后适用于所有情况,以及我应该如何有效地将我的按钮传递给它。

我认为没有必要使用通知。在不更改大量代码的情况下,一种方法是将手势识别器添加到按钮,并在创建按钮时使用其各自的索引预先设置按钮的标签。

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

如果您有权访问该按钮,则在发布通知时,您可以做的是。在视图中添加观察点将出现

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])

最新更新