Search code examples
iosxcodeuiviewuibuttonuinavigationitem

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'


Solution

  • 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];