您的位置:首页 > 其它

关于tableView和cell的小知识点总结

2016-10-26 11:43 330 查看

1.注册cell

//自定义cell使用xib时,注册cell
- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier
//重用时调用cell的方法
- (void)awakeFromNib;

//自定义cell未使用xib时,注册cell
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier
//重用时调用cell的方法
- (id)initWithStyle: withReusebleCellIdentifier:


2.重用cell

//当重用cell使用dequeueReusableCellWithIdentifier:(NSString *)identifier时
//不必向tableView注册cell的Identifier
//但需要判断获取得cell是否为nil

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * tableViewIdentifier = @"tableViewCellIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:tableViewIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:tableViewIdentifier];
}
}
/*
* 当重用cell使用dequeueReusableCellWithIdentifier:(NSString *)identifier
* forIndexPath:(NSIndexPath *)indexPath时
* 必须向tableView注册cell的Identifier
* 不必判断获取得cell是否为空
* runtime将使用注册时提供的资源新建一个cell并返回
*/

- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier
forIndexPath:(NSIndexPath *)indexPath;


3.自定义cell时记得将内容添加到self.contentView而不是cell本身。

4.当cell的分割线宽度不能占满全屏宽度的时候,可以设置:

[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];


5.当你想去掉tableView多余的分割线的时候,可以将尾部视图设置为0达到效果

self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];


6.设置cell的背景颜色

直接在cellForRow方法中设置是无效的

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
因为tableView会调整背景来改变cell的选择状态,



必须要在willDisplayCell中设置才会生效

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;

7.tableView不从顶部开始加载

其实从偏移的高度就可以看出来与navigationBar有关系,有导航栏的scrollView会默认下移64高度,所以要将属性automaticallyAdjustsScrollViewInsets设置为NO就可以了,当涉及到父控制器以及子控制器时,只需初始化父控制器的该属性即可。

8.tableViewCell添加侧滑删除

该功能在8.0添加新接口以后实现起来非常简单,实现代理方法即可

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewRowAction * deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[self.dataSourceArray removeObjectAtIndex:indexPath.row];
[self.tableView reloadData];
}];
return @[deleteAction];//注意最后要返回装有所有action的数组
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: