ios - 向NotificationCenter观察者添加参数UIbutton

标签 ios swift uibutton nsnotificationcenter

我有一个通知观察器,它触发一个采用 UIButton 类型参数的函数。

我一直在努力让通知发挥作用,但由于某种原因,我收到无法识别的选择器发送到实例

以下是我的代码:

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 以及随后适用于所有情况,以及我应该如何有效地将按钮传递给它。

最佳答案

我认为没有必要使用通知。一种无需更改大量代码的方法是将GestureRecognizer 添加到按钮,并在创建按钮时预先设置按钮的标记及其各自的索引。

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函数中,点击按钮时应该做的是发布通知而不是添加观察者。

关于ios - 向NotificationCenter观察者添加参数UIbutton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323803/

相关文章:

ios - 一秒钟后 UIButton 退出突出显示模式

ios - 着陆重复事件不起作用

ios - 是否可以缓存 iPhone UIWebView 中加载的资源?

ios - 将 XCode 从 7.1.1 更新到 7.2 会导致警告和构建错误

ios - 如何在 UITableView 中的图像中添加事件指示器?

ios - 快速添加多个 slider 的值然后取平均值?

swift - 函数的枚举参数

objective-c - 在 UIScrollView 中释放带有图像的不可见按钮

ios - coreData executeFetchRequest 方法的竞争条件导致 nil 数据的问题

ios - 使用 UISearchDisplayController 时,弹出窗口不会显示在 iPad View Controller 上