温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

轻松使用富文本

发布时间:2020-06-22 23:40:27 来源:网络 阅读:332 作者:xinji0702 栏目:开发技术

最后发现需要6.0以后,因为nsfontattributename之类的是6.0以后的api

    长久以来,我以为富文本是一种在ios中使用特别麻烦的事情,但是不经意的研究发现,其实并没有那么难!

   以下的代码实现了uilabel中放置富文本。


NSMutableAttributedString *richTask = [[NSMutableAttributedString alloc] initWithString:task];
    NSDictionary *urgentAttributes = @{NSFontAttributeName : [UIFont fontWithName:@"Courier" size:24],
                                       NSStrokeWidthAttributeName : @3.0,NSStrokeColorAttributeName:[UIColor greenColor]};
    [richTask setAttributes:urgentAttributes range:urgentRange];





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
                                                                   
    NSString *identifier = nil;
    NSString *task = [self.tasks objectAtIndex:indexPath.row];
    NSRange urgentRange = [task rangeOfString:@"URGENT"];
    if (urgentRange.location == NSNotFound) {
        identifier = @"plainCell";
    } else {
        identifier = @"attentionCell";
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                                                                   
    // Configure the cell...
                                                                   
    UILabel *cellLabel = (UILabel *)[cell viewWithTag:1];
    NSMutableAttributedString *richTask = [[NSMutableAttributedString alloc] initWithString:task];
    NSDictionary *urgentAttributes = @{NSFontAttributeName : [UIFont fontWithName:@"Courier" size:24],
                                       NSStrokeWidthAttributeName : @3.0,NSStrokeColorAttributeName:[UIColor greenColor]};
    [richTask setAttributes:urgentAttributes range:urgentRange];
    if (urgentRange.location != NSNotFound) {
        NSRange otherPartRange = NSMakeRange(urgentRange.length+urgentRange.location, task.length-urgentRange.length);
        NSDictionary* otherPartAttributes = @{NSFontAttributeName : [UIFont fontWithName:@"Courier" size:12],
                                              NSStrokeWidthAttributeName : @0,NSStrokeColorAttributeName:[UIColor redColor]};
        [richTask setAttributes:otherPartAttributes range:otherPartRange];
    }
                                                                   
    cellLabel.attributedText = richTask;
                                                                   
    return cell;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI