【问题标题】:Setting font size of UIBarButtonItem设置 UIBarButtonItem 的字体大小
【发布时间】:2018-09-11 22:37:46
【问题描述】:

我正在使用以下代码创建UIBarButtonItem

    let rightItem = UIBarButtonItem(title: "➞", style: UIBarButtonItemStyle.Plain, target: self, action: "navigateToViewTwo")

    if let font = UIFont(name: "System", size: 25.0) {
        rightItem.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)}

    navigationController?.navigationBar.topItem?.rightBarButtonItem = rightItem

该按钮应该显示一个右箭头,它确实如此。问题是字体没有控制按钮的大小。我得到以下信息:

仅在使用系统字体时发生。我用 Helvetica 试了一下,结果如下:

箭头肯定更大,但在导航栏上也太高了。如果我旋转屏幕,它看起来很糟糕。

箭头太高了,看起来不合适。与左侧的“项目”按钮相比,看看它的外观?那个被拖放了。

如何调整箭头以使其大小正确,并位于屏幕上的正确位置?

【问题讨论】:

    标签: swift uibarbuttonitem


    【解决方案1】:

    你必须设置标题边缘插入

    使用自定义视图

    var btn = UIButton.buttonWithType(UIButtonType.System) as! UIButton
    btn.frame = CGRectMake(10, 20, 50, 50)
    btn.setTitle("➞", forState: UIControlState.Normal)
    btn.titleLabel?.font = UIFont(name: "Helvetica" , size: 17)
    btn.titleEdgeInsets = UIEdgeInsetsMake(5, 0, 0, 0)
    btn.addTarget(self, action: Selector("navigateToViewTwo"), forControlEvents: UIControlEvents.TouchUpInside)
    var right = UIBarButtonItem(customView: btn)
    

    像你做的那样正常

    var rightItem = UIBarButtonItem(title: "➞", style: UIBarButtonItemStyle.Plain, target: self, action: "navigateToViewTwo")
    rightItem.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Helvetica", size: 17.0)!], forState: UIControlState.Normal)
    rightItem.setTitlePositionAdjustment(UIOffsetMake(0.0, 5.0), forBarMetrics: UIBarMetrics.Default)
    

    设置两者进行比较,只需添加看起来像面糊的:

    navigationController?.navigationBar.topItem?.rightBarButtonItems = [rightItem,right]
    

    结果:

    希望对你有帮助。

    【讨论】:

    • 这对 rightBarButtonItems 很有效,但对 backBarButtonItems 根本不起作用。 backBarItem 不受字体设置的影响。它保持相同的大小。是否还需要做任何其他事情才能使其适用于所有按钮?
    • @ScottKilbourn 如果你想在左侧添加按钮,有leftBarButtonItems
    • @ScottKilbourn 如果你只想设置一个按钮,那么rightBarButtonItemleftBarButtonItem
    【解决方案2】:
    UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor(red:0.12, green:0.28, blue:0.40, alpha:1.0), NSAttributedStringKey.font: UIFont(name: "GalanoGrotesque-SemiBold", size: 18)!], for: .normal)
    

    【讨论】:

      【解决方案3】:

      我之前也遇到过这个问题,我决定使用自定义视图来处理,如下:

          var view = // create your custom view
          var btnMenu = UIBarButtonItem(customView: view)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        • 2014-09-03
        • 2020-06-12
        • 2017-04-29
        • 2014-10-21
        • 1970-01-01
        相关资源
        最近更新 更多