UITableView分隔符插入0不起作用
iOS在单元格和表视图上引入了layoutMargins属性。
此属性在iOS 7.0上不可用,因此您需要确保在分配前检查一下!
此外,Apple已向您的单元格中添加了一个属性,以防止其继承您的Table View的边距设置。 设置此属性后,将允许单元独立于表格视图配置其自身的边距。 将其视为替代。
此属性称为preservesSuperviewLayoutMargins
,并将其设置为NO
将允许单元格的layoutMargin
设置覆盖在TableView上设置的所有layoutMargin
。 既节省时间( 您不必修改表视图的设置 ),又更简洁。 请参阅Mike Abdullah的答案以获取详细说明。
注意:下面是 Mike Abdullah的回答所表示 的 单元格级边距设置 的干净实现 。 设置单元格的preservesSuperviewLayoutMargins = NO将确保您的表视图不会覆盖单元格设置。 如果您实际上希望整个表格视图具有一致的边距,请相应地调整代码。
设置您的单元格边距:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除分隔符插图
如果([单元格responsToSelector:@selector(setSeparatorInset :)]){
[cell setSeparatorInset:UIEdgeInsetsZero];
} //防止单元格继承表视图的边距设置
如果([单元格responsesToSelector:@selector(setPreservesSuperviewLayoutMargins :)]){
[cell setPreservesSuperviewLayoutMargins:NO];
} //明确设置单元格的布局边距
如果([单元格responsesToSelector:@selector(setLayoutMargins :)]){
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
斯威夫特4:
func tableView(_ tableView:UITableView,willDisplay cell:UITableViewCell,forRowAt indexPath:IndexPath){
//删除分隔符插图
如果cell.responds(to:#selector(setter:UITableViewCell.separatorInset)){
cell.separatorInset = .zero
}
//防止单元格继承表视图的边距设置
如果cell.responds(to:#selector(setter:UITableViewCell.preservesSuperviewLayoutMargins)){
cell.preservesSuperviewLayoutMargins = false
}
//明确设置单元格的布局边距
如果cell.responds(to:#selector(setter:UITableViewCell.layoutMargins)){
cell.layoutMargins = .zero
}
}
将单元格上的preservesSuperviewLayoutMargins属性设置为NO 应该可以防止表格视图覆盖单元格边距。 在某些情况下,它似乎无法正常运行。
如果全部失败,则可以强行使用Table View边距:
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews]; //强制使用表格边距(这可能是个坏主意)
如果([self.tableView responsesToSelector:@selector(setSeparatorInset :)]){
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
} if([[self.tableView responsesToSelector:@selector(setLayoutMargins :)]){
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
}
斯威夫特4:
func viewDidLayoutSubviews(){
super.viewDidLayoutSubviews()
//强制使用表格边距(这可能是个坏主意)
如果tableView.responds(to:#selector(setter:UITableView.separatorInset)){
tableView.separatorInset = .zero
}
if tableView.responds(to:#selector(setter:UITableView.layoutMargins)){
tableView.layoutMargins = .zero
}
}
iOS 9中的可能更改。如果要自定义插图或边距,则可能需要将表视图的cellLayoutMarginsFollowReadableWidth
为NO
。 您的里程可能会有所不同,但记录不充分。
此属性仅在iOS 9中存在,因此请确保在设置前进行检查。
if([myTableView responsesToSelector:@selector(setCellLayoutMarginsFollowReadableWidth :)])
{
myTableView.cellLayoutMarginsFollowReadableWidth = NO;
}
斯威夫特4:
如果myTableView.responds(to:#selector(setter:self.cellLayoutMarginsFollowReadableWidth)){
myTableView.cellLayoutMarginsFollowReadableWidth = false
}
上面显示了纯Interface Builder方法: