#import <UIKit/UIKit.h>
#define VIEW_WIDTH self.view.bounds.size.width
#define VIEW_HEIGHT self.view.bounds.size.height
@interface HomeViewController :UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *_tableView;
@private
NSInteger indexP;
}
@property (nonatomic,retain)NSArray *listArray;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
self.listArray = [UIFontfamilyNames];//所有字体名称
_tableView = [[UITableViewalloc]initWithFrame:CGRectMake(0,20, VIEW_WIDTH, VIEW_HEIGHT-20)style:UITableViewStylePlain];
[self.viewaddSubview:_tableView];
//实现数据源方法
_tableView.dataSource =self;
//实现委托
_tableView.delegate =self;
indexP = -1; //使第一次lastPath无值
}
#pragma mark - UITableView DataSource
//section中包含row的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return_listArray.count;
}
//创建单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//定义一个静态标识符
static NSString *cellIndentifier =@"cell";
//检查是否有闲置单元格,重新赋值
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
//创建单元格
if (cell == nil) {
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIndentifier];
}
//给cell赋值
NSString *fontName = [self.listArrayobjectAtIndex:indexPath.row];
cell.textLabel.text = fontName;
cell.textLabel.textColor = [UIColorredColor];
cell.textLabel.font = [UIFontfontWithName:fontName size:24];
//解决重用单元格打勾情况
if (indexP == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
#pragma mark - UITableView Delegate
/* question
* 1、单选
* 2、重用
*/
//将选中和单元格打勾
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSIndexPath -> max 取消上一次选中
NSIndexPath *lastIndex = [NSIndexPathindexPathForRow:indexPinSection:0];
UITableViewCell *lastcell = [tableView cellForRowAtIndexPath:lastIndex];
lastcell.accessoryType = UITableViewCellAccessoryNone;
//选中了新的一行
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType =UITableViewCellAccessoryCheckmark;
//记录选中的indexPath.row
indexP = indexPath.row;
//设置一个方法,使打勾的单元格,5秒钟后取消选中
[_tableView performSelector:@selector(deselectRowAtIndexPath:animated:)withObject:indexPath afterDelay:0.5];
}
//不选中时调用,用的比较少,与上面5秒钟后取消选中不能同用
//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
// NSLog(@"didDeselectRowAtIndexPath:%ld",(long)indexPath.row);
//}