Scott Kilbourn
Scott Kilbourn

Reputation: 1586

Setting font size of UIBarButtonItem

I am creating a UIBarButtonItem with the following code.

    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

The button should display a right arrow, and it does. The problem is that the font is not controlling the size of the button. I get the following:

enter image description here

The only happens when using the System font. I tried it with Helvetica, and I got the following:

enter image description here

The arrow is definitely larger, but it is also too high on the nav bar. If I rotate the screen, it looks bad.

enter image description here

The arrow is too high, and looks out of place. See how it looks, compared to the Item button on the left? That one was dragged and dropped.

How can I adjust the arrow so that it is in the correct size, and in the correct place on the screen?

Upvotes: 5

Views: 14671

Answers (3)

Alex_Burla
Alex_Burla

Reputation: 810

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)

Upvotes: 7

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

You have to set title edge insets

With CustomView

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)

With Normal as you have done

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)

Set both for comparison, just add it which looks batter :

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

Results :

enter image description here

Hope it will help you.

Upvotes: 15

Siu Chung Chan
Siu Chung Chan

Reputation: 1686

I have encounter this problem before, and I decide to use a custom view to handle this as follow:

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

Upvotes: 1

Related Questions