Search code examples
iosobjective-cuibuttonuilabelnsattributedstring

Is there a way to implicitly make an button be multi-line?


I want a button that is similar to this:

ONE
TWO

Where one word is over the other. However, it may be:

THREE
FOUR

Or any number, really. Is there a way with NSAttributedStrings that I can say to always have a line-break after the first word?


Solution

  • It's really not about NSAttributedString or NSString, but rather about the button itself. You may think of subclassing UIButton and overriding setTitle:forState: to automatically replace the first space with a \n.

    Specifically the setTitle:forState: would look something like this

    - (void)setTitle:(NSString *)title forState:(UIControlState)state {
        NSRange firstSpaceRanger = [title rangeOfString:@" "];
        if (firstSpaceRanger.location != NSNotFound) {
            title = [title stringByReplacingCharactersInRange:firstSpaceRanger withString:@"\n"];
        }
        [super setTitle:title forState:state];
    }
    

    For instance, given one two three this will produce

    one
    two three
    

    In order to make the button multiline you can do, in the UIButton initializer:

    self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    

    Yes, firstSpaceRanger is intentional. I couldn't resist.