ios - NSNotification 用户信息在按下按钮时保持堆叠

标签 ios swift nsnotificationcenter nsnotifications nsnotification

所以我有两个 View Controller ,它们同时显示。目标如下:当我按下菜单时,它会返回一个索引。这将通知其他屏幕它需要更新。

我正在做以下事情:

Controller A(菜单)

   func carbonTabSwipeNavigation(carbonTabSwipeNavigation: CarbonTabSwipeNavigation, didMoveAtIndex index: UInt) {
    //NSLog("Did move at index: %ld", index)
        //NSNotification to send data
        NSNotificationCenter.defaultCenter().postNotificationName(NotificationNames.GetIndexCarbonKit, object: nil, userInfo: ["clickedIndex" : Int(index)])
}

Controller B(接收器)

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchResults.didReceiveNotification(_:)), name: NotificationNames.GetIndexCarbonKit, object: nil)
}


func didReceiveNotification(notification: NSNotification) {
    let index:Dictionary<String,Int> = notification.userInfo as! Dictionary<String,Int>
    let messageFromNotification = index["clickedIndex"]
    print(" SearchResults now shows index: \(messageFromNotification)")
}

我的问题如下:我将索引从 A 发送到 B 的词典不断堆叠。因此,如果我多次按下菜单,我的输出如下:

 SearchResults now shows index: Optional(0)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(2)
 SearchResults now shows index: Optional(2)
 SearchResults now shows index: Optional(2)
 SearchResults now shows index: Optional(3)
 SearchResults now shows index: Optional(3)
 SearchResults now shows index: Optional(3)
 SearchResults now shows index: Optional(3)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(1)
 SearchResults now shows index: Optional(1)

如何只获取最后一个索引?我不需要一堆其他的。

最佳答案

自己找到了正确答案。显然,我所要做的就是将 NotificationCenter 添加到 ViewWillAppear,并在 ViewWillDisappear 处将其删除。当我在 View 之间切换菜单时(相同 View 的 4 倍),它只返回一个值。

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SearchResults.didReceiveNotification(_:)), name: NotificationNames.GetIndexCarbonKit, object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func didReceiveNotification(notification: NSNotification) {
    let index:Dictionary<String,Int> = notification.userInfo as! Dictionary<String,Int>
    self.currentIndex = (index.first?.1)!
    print(currentIndex)
}

关于ios - NSNotification 用户信息在按下按钮时保持堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859900/

相关文章:

ios - 在 textView 中添加 Emoji 然后 Crash Swift

ios - UIImagePickerController - 自定义覆盖上的重新拍摄按钮(Swift)

ios - 无法更新自定义 UITableViewCell 中 UITextView 的文本

ios - React-native iOS 构建失败

ios - 在 Swift 3 中获取多级字典信息的最佳方法是什么

swifty 并分配数组

swift - 为只读计算属性赋值

ios - 每次点击屏幕时都会调用 NSNotification

ios - 如何使用 NSNotificationCenter 自动更新列表项状态?

ios - UIButton - 给按钮一个 Action ?