我有这个代码并且它正在运行(来自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下触发。不是按下按钮,或其他东西。
谢谢。答案 0 :(得分: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参数。
希望这有帮助。