Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set button for navigationItem titleView?

I want to programmatically set button for navigationItem.titleView.

I tried with following code but with no success;

UIBarButtonItem *navigationTitleButton = [[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStyleBordered target:self action:@selector(backToHOmePage)];

navigationTitleButton.image = [UIImage imageNamed:@"title.png"];

self.navigationItem.titleView = navigationTitleButton;

Warnng says: Incompatible pointer types assigning to 'UIView *' from 'UIBarButtonItem *__strong'

like image 725
iWizard Avatar asked Nov 12 '12 09:11

iWizard


3 Answers

Try to use this code see if it works for you

UIView * container = [[UIView alloc]initWithFrame:CGRectZero];
UIButton * button = [[UIButton alloc]initWithFrame:CGRectZero];
[button addTarget:self action:@selector(backToHOmePage) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:@"clanak_default.png"] forState:UIControlStateNormal];
[button sizeToFit];
[container addSubview:button];
[button release];
[container sizeToFit];
self.navigationItem.titleView = container;
[container release];
like image 173
Janub Avatar answered Oct 03 '22 04:10

Janub


You dont have to create BarItem, you need to create UIView class object;

ARC

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
view.backgroundColor = [UIColor clearColor];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = view.frame;

[view addSubview:button];

self.navigationItem.titleView = view;

or

   UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   button.frame = CGRectMake(0, 0, 40, 40);
   self.navigationItem.titleView = button;
like image 40
Evgeniy S Avatar answered Oct 03 '22 04:10

Evgeniy S


Swift version:

var button =  UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0, 100, 40) as CGRect
button.backgroundColor = UIColor.redColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: Selector("clickOnButton:"), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = button

Here you can see in last line button is directly set to the titleView of navigationItem which will add button at the center of navigation bar.

Action method for button is below:

func clickOnButton(button: UIButton) {

}
like image 35
Esqarrouth Avatar answered Oct 03 '22 04:10

Esqarrouth