Swift:将UIButton转换为UIBarButtonItem,它真的必须这么复杂吗?

时间:2017-06-26 16:18:39

标签: ios swift swift3 uinavigationbar uibarbuttonitem

我在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的扩展程序。这启用了此代码。

处理iOS 9和iOS 10的解决方案

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
    }
}

这是我的扩展程序的代码。

扩展UIButton

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
    }
}

问题1:为什么在UIStackView中定位UIButtons不适用于iOS 9?

问题2:我的分机是否不必要地复杂?或者以某种方式不安全?

1 个答案:

答案 0 :(得分:1)

扩展名可以简化

extension UIButton {
    func toBarButtonItem() -> UIBarButtonItem? {
        return UIBarButtonItem(customView: self)
    }
}