Dvole Dvole - 1 year ago 247
iOS Question

How to make custom UIBarButtonItem with image and label?

I would like to make a custom UIBarButtonItem that contains both image and text, something like this:

enter image description here

I tried subclassing UIBarButtonItem and overriding this method:

- (UIView *)customView
if (!self.storedView) {

UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:self.image];
tempImageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
tempLabel.text = @"text";
[temp addSubview:tempImageView];
[temp addSubview:tempLabel];
self.storedView = temp;
return self.storedView;

And I use it like this:

UIBarButtonItem *left = [[LeftItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsPressed)];
left.title = @"Settings";
left.image = [UIImage imageNamed:@"settings.png"];
self.navigationItem.leftBarButtonItem = left;

But using this I only get the image, but not label. What am I doing wrong?

Answer Source
UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download