1)效果展示
屏幕快照 2019-07-26 下午2.37.20.png
2)源码分享
- (UILabel *)targetLabelWithTitle:(NSString *)title{
UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(0,self.view.frame.size.height /2, self.view.frame.size.width, 100);
label.textColor = [UIColor orangeColor];
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont boldSystemFontOfSize:30.0f];
NSRange startRange = [title rangeOfString:@"("];
NSRange endRange = [title rangeOfString:@")"];
NSRange range = NSMakeRange(startRange.location + startRange.length,endRange.location - (startRange.location + startRange.length));
NSString *beforeString = [title substringToIndex:startRange.location];
NSString *resultString = [title substringWithRange:range];
//重置去掉"()"后的title
NSString *handleString = [NSString stringWithFormat:@"%@%@",beforeString,resultString];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:handleString];
NSRange resultRange = NSMakeRange([[attributedString string] rangeOfString:resultString].location, [[attributedString string] rangeOfString:resultString].length);
//需要的特殊颜色
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:resultRange];
//设置属性字符串
label.attributedText = attributedString;
return label;
}
3)使用方法
-
① 在你需要的地方创建Label;
-
② 传入带括号的(字符串)
-
③ 括号内的文字就是需要改变的目标颜色
UILabel *l = [self targetLabelWithTitle:@"啊哈哈哈(想不到吧)"]; [self.view addSubview:l];
网友评论