12

a のテキストを黒にする必要がありますが、テキストのUILabel下に薄い灰色の下線が引かれています。これは または で可能ですNSAttributedStringTTTAttributedLabel? または、Core Graphics を使用したカスタム描画が必要ですか?

明確化: 別の色の下線に特定の色のテキストが必要です。例: 赤い下線に青いテキスト。

4

6 に答える 6

22

以下のようにできNSAttributedStringます。

NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:@"you string"];
[string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, string.length)];//TextColor
[string addAttribute:NSUnderlineStyleAttributeName value:underlineNumber range:NSMakeRange(0, string.length)];//Underline color
[string addAttribute:NSUnderlineColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, string.length)];//TextColor
 yourlabel. attributedText = string;

注:この投稿のように、特定の範囲の文字列に下線を引くこともできます。また、注意してください、それはios6 +のみで動作します。

于 2014-03-15T05:29:21.017 に答える
1
// Print `str` in black, and underline the word STRING in gray.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"This is my STRING"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, str.length-7)];
[str addAttribute:NSUnderlineColorAttributeName value:[UIColor grayColor] range:NSMakeRange([str length]-6, 6)];
[str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange([str length]-6, 6)];

_label.attributedText = str; // assuming you have an iVar name `label`
于 2014-03-15T05:59:50.763 に答える
0
m-farhan.com  farhan will be underlined

//-----------------------------
    // Create attributed string
    //-----------------------------
    NSString *str = @"m-Farhan.com";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];

    // Add attribute NSUnderlineStyleAttributeName
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(2, 4)];

    // Set background color for entire range
    [attributedString addAttribute:NSBackgroundColorAttributeName
      value:[UIColor colorWithRed:0.103 green:0.305 blue:0.492 alpha:1.000]
      range:NSMakeRange(0, [attributedString length])];

    // Define label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 280, 80)];
    [label setLineBreakMode:UILineBreakModeWordWrap];
    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextAlignment:UITextAlignmentLeft];

    // Set label text to attributed string
    [label setAttributedText:attributedString];
    [[self view] addSubview:label];
于 2014-03-15T05:33:09.917 に答える
-1

迅速に、を使用しますNSAttributedString.Key.underlineColor

于 2021-07-11T05:57:09.453 に答える