设置 UIBarButtonItem 的字体大小

Setting font size of UIBarButtonItem

我正在使用以下代码创建 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 试了一下,结果如下:

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

箭头太高,看起来不合适。看看它与左侧的 Item 按钮相比如何?那个被拖拽掉了

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

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

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

您必须设置标题边缘插入

使用自定义视图

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)

像你所做的那样使用 Normal

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]

结果:

希望对您有所帮助。

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)