在 Swift 中获取 UIBarButtonItem 的视图
Posted
技术标签:
【中文标题】在 Swift 中获取 UIBarButtonItem 的视图【英文标题】:Get the View of UIBarButtonItem in Swift 【发布时间】:2017-06-15 00:27:29 【问题描述】:希望这是一个简单的问题。我正在尝试获取 UIBarButtonItem 的 UIView。看着下面的*** question我想出了下面的代码:
let notificationButton = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)
let notificationView = notificationButton.value(forKey: "view") as? UIView
但是,notificationView 为 nil。那么,关于我未能从链接的 *** 问题中解释的内容的想法?
【问题讨论】:
为什么需要它? NRitH:我想修改图片添加徽章 你是否在 navigationItem 中添加了 notificationButton? DS Dharma:您不会将 navigationButton 添加到 navigationItem 中,而是像这样分配它:self.navigationItem.rightBarButtonItem = notificationButton 【参考方案1】:从 ios 11 开始,此代码将不起作用,因为下面的代码行不会转换 UIView。它也算作私有 API,似乎不会通过 AppStore 审查。
guard let view = self.value(forKey: "view") as? UIView else return
Thread on: forums.developer.apple
【讨论】:
【参考方案2】:所以,DS Dharma 给了我一个最终奏效的想法。 "view" 值只有在分配给工具栏导航项后才可用,如下所示:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem?.addBadge(number: 0, withOffset: CGPoint(x: 7.0, y: 0.0) , andColor: UIColor.black, andFilled: true)
addBadge() 函数需要 UIView 的地方。顺便说一句,如果有人想知道,addBadge 函数取自这篇文章:http://www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem
如果您需要此功能,强烈推荐。
【讨论】:
不幸的是,当您有多个酒吧项目时,这不起作用。例如self.navigationItem.rightBarButtomItems.append(barBtn)以上是关于在 Swift 中获取 UIBarButtonItem 的视图的主要内容,如果未能解决你的问题,请参考以下文章
使用 NSCoding 保存 TableView 单元格的重新排序