リッチテキストを簡単に使用


最後に発見するには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;
}