0

我有这段代码并且它正在工作(来自https://stackoverflow.com/a/3586943/1187014的回答),但我想尝试稍微修改一下:

NSString *text = @"Forgot password?";

if ([_labelForgotPassword respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings
    const CGFloat fontSize = 13;
    UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
    UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
    UIColor *foregroundColor = [UIColor whiteColor];

    // Create the attributes
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                           boldFont, NSFontAttributeName,
                           foregroundColor, NSForegroundColorAttributeName, nil];
    NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                              regularFont, NSFontAttributeName, nil];
    const NSRange range = NSMakeRange(16,0);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
    [[NSMutableAttributedString alloc] initWithString:text
                                           attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_labelForgotPassword setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_labelForgotPassword setText:text];

}

如果我有多个文本怎么办,比如说:

NSString *text1 = @"Forgot password?"; // relates with UILabel _labelForgotPassword
NSString *text2 = @"I agree with terms and condition"; // relates with UILabel _labelTerms
NSString *text3 = @"Your country is not listed yet?"; // relates with UILabel _labelCountry

我想到的第一种方法是嵌套 IF,但是当我有很多需要归因的文本时,嵌套 IF 会非常难看,对吧?

那么,如何将该代码创建到一个方法中,以便我可以只提供字符串、_label 的名称、范围等并将结果返回给特定的 UILabel。而且都是在viewDidLoad下触发的。不是通过按下按钮或其他方式。

谢谢你。

4

1 回答 1

0

我的理解是您希望将相同的属性逻辑应用于所有标签。如果您只想将其用于 UILabel,则可以在 UILabel 上创建一个类别。

类别的语法应该是这样的:

+(NSMutableAttributedString *) convertToAttributedText: (NSString *) text withFont: (UIFont *) font
{
   // write the above logic here
   //return the attributed text;
}

您可以将 text1 / text2 / text3 传递给此 api,您将获得属性文本。

label.attributedtext = [NSString convertToAttributedText: text withFont:font];

您可以根据需要配置此 API 参数。

希望这可以帮助。

于 2013-09-16T06:27:42.583 回答