iOS 原生富文本显示图文

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor= [UIColor blackColor];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, CGRectGetWidth([UIScreen mainScreen].bounds)-20, 200)];
    label.numberOfLines = 0;
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:@"气象通知:\n"];
    [arr addObject:@"今天的雨下的有点大"];
    [arr addObject:@"今天的雨下的比依萍要钱的那天还要大"];
    label.attributedText = [self attributedImageName:@"001" imageFram:CGRectZero arrStr:arr];
    [self.view addSubview:label];
    
    
}

#pragma mark ----------------------- 富文本标题 ------------------------
-(NSAttributedString*)attributedImageName:(NSString *)imageName  imageFram:(CGRect)imageFram   arrStr:(NSMutableArray *)arrstr
{
    //创建富文本
    NSMutableAttributedString *atring = [[NSMutableAttributedString alloc]init];
    for (int i = 0; i< arrstr.count; i++)
    {
        UIColor *color;
        if (i == 0)
        {
            color = [UIColor redColor];
        }
        else if (i == 1)
        {
            color = [UIColor greenColor];
        }
        else
        {
            color = [UIColor blueColor];
        }
        NSString *str = [NSString stringWithFormat:@"%@",arrstr[i]];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
        [attri addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0,str.length)];
        [atring appendAttributedString:attri];
    }
    
    // NSTextAttachment可以将要插入的图片作为特殊字符处理
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    // 定义图片内容及位置和大小
    attch.image = [UIImage imageNamed:imageName];
    if (CGRectGetWidth(imageFram) > 0)
    {
        attch.bounds = imageFram;
    }
    else
    {
        attch.bounds = CGRectMake(0, -1, 17, 17);
    }
    //创建带有图片的富文本
    NSAttributedString *stringIm = [NSAttributedString attributedStringWithAttachment:attch];
    //将图片放在第一位
    [atring insertAttributedString:stringIm atIndex:0];
    return atring;
}

猜你喜欢

转载自blog.csdn.net/saw471/article/details/81060527
今日推荐