anshuman
anshuman

Reputation: 131

UIBarButtonItem with image and text

I have to create a UIBarButton on the having a globe and a text "Map" written on it.

What I have done:

  1. I have added a UIButton with the image of the globe as backgroundImage.
  2. Set the text on the button.
  3. Then created a UIBarButton initWithCustomView from the above button.
  4. Given it style as Bordered.

Result:

Now what i got is a plane button with the globe image stretched on that which is overlapping with the Text in it.

I have searched for this a lot but i only found links which show the image in background and the text above the button. Nothing like the image and text together.

Can anyone help me in creating it the way it is shown in the attachment.

Upvotes: 2

Views: 3260

Answers (2)

M.B
M.B

Reputation: 885

Use image with @2x. if your graphices are high resolution. according to 640 X 960 px;:-

UIView *parentView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 6,51, 44)];
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 6, 51, 30)];

[btnBack setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal];

[btnBack addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];  

[parentView1 addSubview:btnBack];

[btnBack release];  

UIBarButtonItem *homeBarButtomItem2 = [[UIBarButtonItem alloc] initWithCustomView:parentView1]; 

[parentView1 release];  

[self.navigationItem setLeftBarButtonItem:homeBarButtomItem2];

[homeBarButtomItem2 release];

Upvotes: 0

rptwsthi
rptwsthi

Reputation: 10172

Try this :

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
[button setTitle:@"Title" forState:UIControlStateNormal];
UIImage *butImage_on = [[UIImage imageNamed:@"closebutton_on.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];  
UIImage *butImage_over = [[UIImage imageNamed:@"closebutton_over.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];  
[button setBackgroundImage:butImage_on forState:UIControlStateNormal];  
[button setBackgroundImage:butImage_over forState:UIControlStateHighlighted];  
[button setImage:[UIImage imageNamed:@"globe.png"] forState:UIControlStateNormal];  
[button addTarget:self action:@selector(closeProfilePage) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(0, 0, 61, 30);  

[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 2)];
[button setImageEdgeInsets:UIEdgeInsetsMake(30,
                                         20,
                                         0,
                                         20)];

UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];  
self.navigationItem.leftBarButtonItem = backButton;

Note: you need to manage insets according to your requirements.

Upvotes: 2

Related Questions