UI基础之UITableViewController相关
1> 设置类型为Group
- (instancetype)initWithStyle:(UITableViewStyle)style { return [super initWithStyle:UITableViewStyleGrouped]; }
2> 设置每组cell之间的间距
// 每组头部高度 self.tableView.sectionHeaderHeight = 10; // 每组底部高度 self.tableView.sectionFooterHeight = 0;
3> 设置cell的分隔线
// 去掉分隔线
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
/*-- 设置cell分隔线为全屏 --*/ // 方案一 // 在iOS7之后,tableView会有自己的内边距 // 将内边距清空 self.tableView.separatorInset = UIEdgeInsetsZero; // 在iOS8之后,系统会在每一个控件自动布局时添加默认的内边距 // 清空cell的内边距:考虑重复利用,所以在awakeFromNib中设置一次就可以了 - (void)awakeFromNib { self.layoutMargins = UIEdgeInsetsZero; } // 方案二 // 了解tableView底层实现,通过设置cell的frame实现 // 取消cell分隔线 self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // 设置tableView的背景色 self.tableView.backgroundColor = [UIColor lightGrayColor]; // 在自定义cell中重写setFrame方法 - (void)setFrame:(CGRect)frame { frame.size.height -= 1; [super setFrame:frame]; }
4> 设置tableView的弹簧效果
// 取消弹簧效果 self.tableView.bounces = NO;
5> 设置cell选中时的背景颜色
UIView *backgroundV = [[UIView alloc] initWithFrame:cell.bounds]; backgroundV.backgroundColor = [UIColor whiteColor]; cell.selectedBackgroundView = backgroundV;
6> 设置带箭头的cell样式
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
7> 设置cell文字的字体和颜色
cell.textLabel.font = [UIFont systemFontOfSize:15.0]; cell.textLabel.textColor = [UIColor darkGrayColor];
8> 设置cell中的富文本
NSMutableDictionary *attDict = [NSMutableDictionary dictionary]; attDict[NSFontAttributeName] = [UIFont boldSystemFontOfSize:20.0]; attDict[NSForegroundColorAttributeName] = [UIColor whiteColor]; NSAttributedString *attText = [[NSAttributedString alloc] initWithString:@"安全退出" attributes:attDict]; cell.textLabel.attributedText = attText;
9> 设置cell文字居中
cell.textLabel.textAlignment = NSTextAlignmentCenter;
10> 当tableView为UITableViewStylePlain时,隐藏多余的cell
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
11> 设置tableView的headerView
UITableViewHeaderFooterView *headerView = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)]; headerView.contentView.backgroundColor = [UIColor redColor]; self.tableView.tableHeaderView = headerView;
使用TableView时遇到的坑:
1> [TableView] Setting the background color on UITableViewHeaderFooterView has been deprecated. Please set a custom UIView with your desired background color to the backgroundView property instead.
翻译:不赞成在UITableViewHeaderFooterView上设置背景色。请改为将具有所需背景色的自定义UIView设置为backgroundview属性。
解决方案:使用xib时,添加一个View控件,设置View的背景色。
2>[Warning] Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.
翻译:[警告]仅警告一次:检测到一种情况,其中约束模糊地建议TableView单元格的内容视图的高度为零。我们考虑的是无意的坍塌,而是使用标准高度。
解决方案:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44; }