AlimovAndrei AlimovAndrei - 3 years ago 163
iOS Question

UIBarButtonItem width with a two-line label

I would like to know how can I get rid of spaces to the left and right from a two-line label in UIBarButtonItem, which has its view set by setCustomView as follows:

UIButton* forwardButton = [UIButton buttonWithType:101];

[forwardButton setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];
[forwardButton.titleLabel setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];

[forwardButton setTitle:@"Now\nPlaying" forState:UIControlStateNormal];
[forwardButton addTarget:self action:@selector(openPlayer) forControlEvents:UIControlEventTouchUpInside];

[forwardButton.titleLabel setNumberOfLines:2];
[forwardButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
[forwardButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
[forwardButton.titleLabel setFont:[UIFont boldSystemFontOfSize:10]];

[navButton setCustomView:forwardButton];


Here is the result I get.

The width of the button is as if the label had text written in one line like this.

Answer Source

You could try changing the bounds for the button.

UIButton* forwardButton = [UIButton buttonWithType:101];
[forwardButton setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];
[forwardButton.titleLabel setTransform:CGAffineTransformMakeScale(-1.0, 1.0)];

[forwardButton setTitle:@"Now\nPlaying" forState:UIControlStateNormal];
[forwardButton.titleLabel setNumberOfLines:2];
[forwardButton.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
[forwardButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
[forwardButton.titleLabel setFont:[UIFont boldSystemFontOfSize:10]];

forwardButton.bounds = CGRectMake(0, 0, 30, 30);


UIBarButtonItem* forwardButtonItem = [[UIBarButtonItem alloc] initWithCustomView: forwardButton];
self.navigationItem.rightBarButtonItem = forwardButtonItem;

tested this and works

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download