我在UIButton
上写了一个扩展名,将UIButton
转换为UIBarButtonItem
。
我尝试使用init(customView
UIBarButtonItem
在我的按钮上传递最简单的解决方案,如下所示:
lazy var myButton: UIButton = {
let button = UIButton(type: .custom)
// setting up button here...
return button
}()
let barButtonItem = UIBarButtonItem(customView: myButton)
但我有几个限制问题。实际上我不仅要在导航栏中放一个按钮,还要放三个项目。所以我尝试将我的三个按钮放入UIStackView
,然后设置navigationItem.rightBarButtonItem = UIBarButtonItem(customView: stackView)
,其功能类似于iOS 10上的魅力 。但是在 iOS 9 上,按钮的位置不起作用。
无论如何,我使用UIBarButtonItem
代替UIButton
,但我不想为iOS 9创建UIBarButton
,而为iOS 10创建UIButton
s。所以我写了一个从UIBarButtonItem
s创建UIButton
的扩展程序。这启用了此代码。
func setupNavigationBar() {
if #available(iOS 10.0, *) {
let stackView: UIStackView = [.views(buttons)] //syntax enabled by framework `ViewComposer`: github.com/Sajjon/ViewComposer
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: stackView)
} else {
navigationItem.rightBarButtonItems = buttons.reversed().flatMap { $0.barButtonItem } // syntax enabled by extension below
}
}
这是我的扩展程序的代码。
extension UIButton {
var barButtonItem: UIBarButtonItem? {
return barButtonItem()
}
func barButtonItem(
style: UIBarButtonItemStyle = .plain,
state: UIControlState = .normal,
controlEvent: UIControlEvents = .primaryActionTriggered
) -> UIBarButtonItem? {
guard
let target = allTargets.first,
let selectorName = actions(forTarget: target, forControlEvent: controlEvent)?.first,
case let image = image(for: state), case let title = title(for: state),
(image != nil || title != nil)
else { return nil }
let action = NSSelectorFromString(selectorName)
if let image = image {
return UIBarButtonItem(image: image, style: style, target: target, action: action)
}
if let title = title {
return UIBarButtonItem(title: title, style: style, target: target, action: action)
}
return nil //should not happen
}
}
答案 0 :(得分:1)
扩展名可以简化
extension UIButton {
func toBarButtonItem() -> UIBarButtonItem? {
return UIBarButtonItem(customView: self)
}
}