Underlining text in UIButton

后端 未结 18 1840
终归单人心
终归单人心 2020-11-29 15:56

Can anyone suggest how to underline the title of a UIButton ? I have a UIButton of Custom type, and I want the Title to be underlined, but the Interface Builder does not pr

18条回答
  •  遥遥无期
    2020-11-29 16:23

    From iOS6 it is now possible to use an NSAttributedString to perform underlining (and anything else attributed strings support) in a much more flexible way:

    NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"The Quick Brown Fox"];
    
    [commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];
    
    [button setAttributedTitle:commentString forState:UIControlStateNormal];
    

    Note: added this as another answer - as its a totally different solution to my previous one.

    Edit: oddly (in iOS8 at least) you have to underline the first character otherwise it doesn't work!

    so as a workaround, set the first char underlined with clear colour!

        // underline Terms and condidtions
        NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:@"View Terms and Conditions"];
    
        // workaround for bug in UIButton - first char needs to be underlined for some reason!
        [tncString addAttribute:NSUnderlineStyleAttributeName
                          value:@(NSUnderlineStyleSingle)
                          range:(NSRange){0,1}];
        [tncString addAttribute:NSUnderlineColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0, 1)];
    
    
        [tncString addAttribute:NSUnderlineStyleAttributeName
                          value:@(NSUnderlineStyleSingle)
                          range:(NSRange){5,[tncString length] - 5}];
    
        [tncBtn setAttributedTitle:tncString forState:UIControlStateNormal];
    

提交回复
热议问题