如果我想创建一些格式如下的字符串:
字符串是标签的文本属性。此字符串中的某些字符具有与其他字符不同的颜色。有些字符带有下划线并有链接,当我点击字符时,会弹出其他视图。
有人可以告诉我如何实现这种效果吗?
如果您支持 iOS < 6,最好使用 3rd 方组件,例如TTTAttributedLabel。否则使用attributedText
的属性UILabel
。
NSDictionary *colors = [[NSDictionary alloc] initWithObjectsAndKeys: [UIColor blueColor], @"Hyd", [UIColor brownColor], @"Bang", [UIColor orangeColor], @"Delhi", [UIColor yellowColor], @"Gujarat", nil];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@""];
for (NSString *word in colors) {
UIColor *color = [colors objectForKey:word];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
NSAttributedString *substring = [[NSAttributedString alloc] initWithString:word attributes:attributes];
[attributeString appendAttributedString:substring];
}