一个小 demo, 在 UITableView 的 cell 上用不同的字体打印同一句话, 用来展示 iOS 中不字体的效果.
//
// Created by 程序猿 on 15/9/7.
// Copyright (c) 2015年 chengxuyuan. All rights reserved.
//
#import "MainViewController.h"
@interface MainViewController () <UITableViewDataSource, UITableViewDelegate> {
// 字体数组
NSMutableArray *_fontName;
// UITableView
UITableView *_myTableView;
}
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_fontName = [NSMutableArray array];
NSArray *fontNamearray = [UIFont familyNames];
for (NSString *str in fontNamearray) {
// 我记得 iOS 中字体之间不用空格隔开, 而是用"-", 之前是疏忽了, 现在加上.
NSString *tempStr = [str stringByReplacingOccurrencesOfString:@" " withString:@"-"];
[_fontName addObject:tempstr];
}
_myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// UITableView 双协议
_myTableView.delegate = self;
_myTableView.dataSource = self;
[_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
[self.view addSubview:_myTableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _fontName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
// 我这里对英文字母, 阿拉伯数组, 中国汉字, 几种常规符号都做了测试.因为我发现大部分字体对汉字无效 o(╯□╰)o
cell.textLabel.text = @"UIFont(English)字体测试(汉字)01234(数字)+-*/!@#$%(符号)";
// 对 cell 的字体进行修改
cell.textLabel.font = [UIFont fontWithName:[_fontName objectAtIndex:indexPath.row] size:20];
cell.textLabel.numberOfLines = 0;
// cell.detailTextLabel.text不知道为啥不好使了, 只能打印了.另外我在点击方法里也写了打印,只要点击想要知道字体的名字就能在控制台打印出来
NSLog(@"%@", [_fontName objectAtIndex:indexPath.row]);
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 120;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%@", [_fontName objectAtIndex:indexPath.row]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
代码如上, 直接复制到 controller 中就可以了.如果发现我写的代码有问题,请联系指正,不胜感激.