【问题标题】:Custom UIBarButtonItem With BG Colour and Text Swift 3自定义 UIBarButtonItem 与 BG 颜色和文本 Swift 3
【发布时间】:2017-01-02 10:54:13
【问题描述】:

我的导航栏右侧有两个按钮。

extension UIViewController {

func setNavigationBarItem() {

    let profileButton   = UIBarButtonItem(title: "?", style: .plain, target: self, action: #selector(didTapProfileButton(_:)))
    navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), profileButton]

    self.slideMenuController()?.removeRightGestures()
    self.slideMenuController()?.addRightGestures()
    }
}

我已经创建了 2 个这样的按钮。但是我想要的 profileButton 具有背景颜色并且该按钮具有角半径。如何添加它使其看起来像:

忽略黑色部分。 UIBarButton 将是黄色背景和圆角半径。

【问题讨论】:

  • 您的实际期望和得到的结果,请具体说明。

标签: ios swift swift3 uibarbuttonitem


【解决方案1】:

为此,您只有一个选项,您需要使用您想要的设计创建 UIButton 实例,然后从该按钮创建 UIBarButtonItem 实例。

let btnProfile = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
btnProfile.setTitle("SY", for: .normal)
btnProfile.backgroundColor = UIColor.yellow
btnProfile.layer.cornerRadius = 4.0
btnProfile.layer.masksToBounds = true

现在从该按钮创建UIBarButtonItem 并使用rightBarButtonItems 进行设置。

navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), UIBarButtonItem(customView: btnProfile)]

【讨论】:

    【解决方案2】:
        let profileButton = UIButton()
        profileButton.frame = CGRect(x:0, y:0, width:30, height:30)
        profileButton.setTitle("SY", for: .normal)
        profileButton.setTitle("SY", for: .highlighted)
        profileButton.backgroundColor = UIColor.yellow
        profileButton.layer.cornerRadius = 5.0
        profileButton.addTarget(self, action: #selector(didTapProfileButton(_:)), for: .touchUpInside)
    
        let rightBarButton = UIBarButtonItem(customView: profileButton)
        self.navigationItem.rightBarButtonItem = rightBarButton
    

    【讨论】:

    • 错误更新了你的答案,我已经回滚了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多