NSMutableAttributedString *mString = [[NSMutableAttributedString alloc] initWithString:@"This is the text and i want to replace something and stuff and stuff"]; mString = [self setSubString:@"stuff" inString:mString withColor:[UIColor greenColor] andFont:[UIFont systemFontOfSize:14.0]]; mString = [self setSubString:@"and" inString:mString withColor:[UIColor redColor] andFont:[UIFont systemFontOfSize:14.0]]; self.labelInfo.attributedText = mString;
效果:
2. Swift 示例
示例1
1 2 3 4 5 6 7
var plainText = title!+" button pressed"; var styleText =NSMutableAttributedString(string: plainText); var attributes : NSDictionary= [NSFontAttributeName : UIFont.boldSystemFontOfSize( statusLabel.font.pointSize )] let nameRange : NSRange= (plainText asNSString).rangeOfString(title!); //styleText.setAttributes(attributes, )) styleText.setAttributes(attributes, range: nameRange); statusLabel.attributedText = styleText;
示例2
1 2 3 4 5 6 7 8 9 10
funcattributedString(plainText : NSString, sString : NSString) -> NSMutableAttributedString { var styleText =NSMutableAttributedString(string: plainText) var font : UIFont=UIFont(name: "Helvetica-BoldOblique", size: 13.0)! var color : UIColor=COLOR_ORANGE var attrs = [NSFontAttributeName : font, NSForegroundColorAttributeName : color] let nameRange : NSRange= (plainText asNSString).rangeOfString(sString) styleText.setAttributes(attrs, range: nameRange) return styleText }