Search code examples
iosobjective-cswiftuibarbuttonitemuitoolbar

How to just add underline below the second line of text in a Bar Button Item?


This is what I want to achieve:

enter image description here

I'm thinking about having two separate attributed strings and combine them together. Not sure if this is the only way?

UPDATE

The button displays "(null)" if using setAttributedTitle. It can display the right string with no attributes if using setTitle.

Still cannot display in the intended way. Any idea?

// Set current bar button attributes
NSMutableAttributedString *currentBarAttributedString = [[NSMutableAttributedString alloc] init];
[currentBarAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"REQUEST\n"
                                                                         attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)}]];
[currentBarAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"EQUIPMENT"
                                                                                   attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}]];
// Initialize buttons and set titles
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setAttributedTitle:currentBarAttributedString forState:UIControlStateNormal];
// [button1 setTitle:[currentBarAttributedString string] forState:UIControlStateNormal];

Solution

  • To add border to text or to change color.here is sample code which is used. use This code in

    - (void)viewDidLoad {
      [super viewDidLoad];
    
      NSString *strFirst = @"Request Equipment";
      NSString *strSecond = @"Active Rentals";
    
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:strFirst
                                                                             attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
                                                                                NSForegroundColorAttributeName:[UIColor yellowColor]}]];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:strSecond
                                                                             attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone),NSForegroundColorAttributeName:[UIColor whiteColor]}]];
    //To use attribute string in button
    [self.btnAttributeString setAttributedTitle:attributedString forState:UIControlStateNormal];
    }
    

    OutPut is

    enter image description here

    Please check this and let me know any issue.