Search code examples
iosuser-interfaceinterface-builderxcode-storyboard

Align UIBarButtonItem Title to prevent overlapping of other Buttons?


I want to create a header toolbar like shown in the image below. It is from the web view of the Twitter app.

enter image description here

I created a UIToolbar and put it at the top. Then I inserted the Buttons left and right and changed the Identifier to get the correct symbols.

My problem is the text in the middle. I create a UIBarButtonItem and placed it between the buttons. Here is my Problem.

  • How to I achieve that the UIBarButtonItem title does not overlap the left and the right button when the title is to long?

In my case:

enter image description here

  • How do I achieve that the title gets ... at the end if it gets to long?
  • How can I set the sub title?
  • How can I achieve that the button is not clickable, i.e., has color black?

Edit Using the answer from @Viral Savaj: Here is what it looks like:

enter image description here


Solution

  • You can set custom title view to the navigation bar like this way.

    //To hide default back button
    self.navigationItem.hidesBackButton=YES;
    
    //Title View for Navigation
    UIView *navTitle1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    [navTitle1 setBackgroundColor:[UIColor lightGrayColor]];
    
    //Left View button and separator
    UIButton *crossBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [crossBarButton setTitle:@"X" forState:UIControlStateNormal];
    
    //Center view with two buttons and seprator for them
    UILabel *topTitle =  [[UILabel alloc] initWithFrame: CGRectMake(50,0, self.view.bounds.size.width-100, 22)];
    topTitle.text = @"text"; 
    topTitle.font = [UIFont systemFontOfSize:25];
    topTitle.lineBreakMode = NSLineBreakByCharWrapping;
    
    
    UILabel *subTitle =  [[UILabel alloc] initWithFrame: CGRectMake(50,20, self.view.bounds.size.width-100, 18)];
    subTitle.text = @"subtext"; 
    subTitle.font = [UIFont systemFontOfSize:18];
    subTitle.lineBreakMode = NSLineBreakByCharWrapping;
    
    //Right button with seprator before that
    UIButton *uploadBarButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-50, 0, 44, 44)];
    [uploadBarButton setTitle:@"U" forState:UIControlStateNormal];
    
    
    [navTitle1 addSubview:crossBarButton];
    [navTitle1 addSubview:topTitle];
    [navTitle1 addSubview:subTitle];
    [navTitle1 addSubview:uploadBarButton];
    self.navigationItem.titleView = navTitle1;
    

    You can refer THIS for more detail.