Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
Scott Kilbourn Avatar asked Nov 29 '22 23:11

Scott Kilbourn


1 Answers

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.

like image 56
Ashish Kakkad Avatar answered Dec 07 '22 00:12

Ashish Kakkad