我有这段代码并且它正在工作(来自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下触发的。不是通过按下按钮或其他方式。
谢谢你。