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'
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];
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;
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With