我有一个应用程序,其中UITableView的分隔符插入设置为自定义值-右0,左0。这在iOS 7中非常有效。x,但是在iOS 8.0中,我看到右边的分隔符被设置为默认值15。即使在xib文件中它设置为0,它仍然不正确地显示。
如何删除UITableViewCell分隔符边距?
我有一个应用程序,其中UITableView的分隔符插入设置为自定义值-右0,左0。这在iOS 7中非常有效。x,但是在iOS 8.0中,我看到右边的分隔符被设置为默认值15。即使在xib文件中它设置为0,它仍然不正确地显示。
如何删除UITableViewCell分隔符边距?
当前回答
Swift 3.0示例:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// removing seperator inset
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
cell.separatorInset = .zero
}
// prevent the cell from inheriting the tableView's margin settings
if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)) {
cell.preservesSuperviewLayoutMargins = false
}
// explicitly setting cell's layout margins
if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
cell.layoutMargins = .zero
}
}
其他回答
在Swift中,这有点烦人,因为layoutmargin是一个属性,所以你必须重写getter和setter。
override var layoutMargins: UIEdgeInsets {
get { return UIEdgeInsetsZero }
set(newVal) {}
}
这将有效地使layoutmargin为只读,这在我的情况下是好的。
对我来说,简单的线条就够了
cell.layoutMargins = UIEdgeInsetsZero
你可以使用一次UIAppearance,在你的应用程序启动时(在UI被加载之前),把它设置为默认的全局设置:
// iOS 7:
[[UITableView appearance] setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[[UITableView appearance] setSeparatorInset:UIEdgeInsetsZero];
[[UITableViewCell appearance] setSeparatorInset:UIEdgeInsetsZero];
// iOS 8:
if ([UITableView instancesRespondToSelector:@selector(setLayoutMargins:)]) {
[[UITableView appearance] setLayoutMargins:UIEdgeInsetsZero];
[[UITableViewCell appearance] setLayoutMargins:UIEdgeInsetsZero];
[[UITableViewCell appearance] setPreservesSuperviewLayoutMargins:NO];
}
这样,你可以保持你的UIViewController的代码干净,如果你想重写它。
以一种比大多数人投票的答案更紧凑的方式……
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cell respondsToSelector:@selector(setSeparatorInset:)] && [cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)] && [cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setPreservesSuperviewLayoutMargins:NO];
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
使用下面的代码片段避免不必要的填充问题UITableView在IOS 8和7。
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)])
{
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}