字符串某个字符修改颜色:
UILabel *titleLabel = [[UILabel alloc]init];
titleLabel.font = smallFont;
titleLabel.text = @"*新密码";
titleLabel.textAlignment = NSTextAlignmentRight;
titleLabel.frame = lxy(5, 20+50, labelSize.width, 20);
NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:titleLabel.text];
//获取要调整颜色的文字位置,调整颜色
NSRange range=[[hintString string]rangeOfString:@"*"];
[hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
titleLabel.attributedText = hintString;
效果如图:
给字符串添加下划线:
UILabel *registLabel = [[UILabel alloc]init];
registLabel.text = @"新用户注册";
registLabel.userInteractionEnabled = YES;
CGSize size = [registLabel.text boundingRectWithSize:CGSizeMake(250, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:registLabel.font forKey:NSFontAttributeName] context:nil].size;
registLabel.frame = lxy((SCREEN_WIDTH-size.width)/2, SCREEN_HEIGHT-20-30, size.width, size.height);
[self.view addSubview:registLabel];
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:registLabel.text attributes:attribtDic];
registLabel.attributedText = attribtStr;
效果图如下:
对一串字符串部分文字 进行字体颜色改变并加上下划线
UILabel *lab_com = [[UILabel alloc]initWithFrame:lxy(0, KScreenH-navHeight-ShowDiff-40, KScreenW, 20)];
lab_com.text = lxyName(@"Company_PrivacyPolicy");
lab_com.font = FONT(18);
lab_com.textColor = UIColor.whiteColor;
lab_com.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:lab_com];
NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:lab_com.text];
NSRange range=[[hintString string]rangeOfString:lxyName(@"PrivacyPolicy")];
[hintString addAttribute:NSForegroundColorAttributeName value:UIBGColor range:range];
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
[hintString addAttributes:attribtDic range:range];
lab_com.attributedText = hintString;
lab_com.userInteractionEnabled = YES;
UITapGestureRecognizer *privacyTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(privacyTapAction)];
[lab_com addGestureRecognizer:privacyTap];
效果图如下