自定义Label的字体颜色和大小

废话不多说,直接上代码,很简单,都是原生的,注意一点就是label不能用.text,要用.attributedText!!

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *_fontArray;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 80.0f;
    _fontArray = [[NSMutableArray alloc] initWithCapacity:242];
    for (NSString * familyName in [UIFont familyNames]) {
        NSLog(@"Font FamilyName = %@",familyName); //*输出字体族科名字
        for (NSString * fontName in [UIFont fontNamesForFamilyName:familyName]) {
            NSLog(@"    %@",fontName);
            [_fontArray addObject:fontName];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _fontArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    NSString * testStr  = @"It has 15 words";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:testStr];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,3)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,4)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(7,4)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:_fontArray[indexPath.row] size:30] range:NSMakeRange(5, 6)];
    cell.textLabel.attributedText = str;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"字体名字:%@",_fontArray[indexPath.row]];
    return cell;
}

@end

转载于:https://www.cnblogs.com/duyuiOS/p/5251707.html

你可能感兴趣的:(自定义Label的字体颜色和大小)