实现一段字符串中部分内容字体颜色大小变化

来源:互联网 发布:22级战舰升级数据 编辑:程序博客网 时间:2024/06/09 19:01
  • 在label、button等等控件中,都可以对需要赋值的字符串设置字体属性,变量名为attributedText:
  • @property(nullable, nonatomic,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
    参数类型为NSAttributedString,当然我们也可以给它赋值NSMutableAttributedString类型的变量,但是在设置字符串属性之前要先将字符串赋值给text参数,具体实现看代码吧

ViewController.m

////  ViewController.m//  部分字体变色demo////  Created by yanll on 15/11/30.//  Copyright © 2015年 yanll. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSString *string = @"大家一起努力学习ios开发";    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 40)];    //必须先赋值string再设置string的属性,否则无效    label.text = string;    //设置需要改变的字符串字体属性    label.attributedText = [self attribute:string changeString:@"努力学习" color:[UIColor greenColor] fount:20];    [self.view addSubview:label];}//实现字体颜色大小的变化- (NSMutableAttributedString *)attribute:(NSString *)String changeString:(NSString *)changeString color:(UIColor *)color fount :(NSInteger)fount{    //创建一个可变属性的字符串    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:String];    //获取需要改变的字符串所在位置    NSRange range = [String rangeOfString:changeString];    //设置需要修改字符串的属性:颜色 大小等等    [string addAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:[UIFont systemFontOfSize:fount],NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle]} range:range];    return string;}@end

当然在设置需要改变的字符串内容必须是在整个字符串中的,否则设置无效,看情况可以加入判断。

0 0