您的位置:首页 > 其它

轻松使用富文本

2013-07-11 11:47 99 查看
最后发现需要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;
}
本文出自 “用心生活” 博客,请务必保留此出处http://derkin2jessie.blog.51cto.com/1009410/1246321
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: