iOS UITableView 单元格缩进

6
我正在通过编程设置UITableView。我希望单元格的内容跨越整个屏幕宽度。我已经成功地将单元格设置为跨越屏幕宽度,但是内容和分隔符仍然有很大的缩进(iPad 截图如下所示)。
以下是在我的视图控制器实现中设置表格视图布局:
- (void) viewDidLoad {
    [super viewDidLoad];

    // table layout
    self.tableView.rowHeight = 192;
    UILayoutGuide *margins = [self.view layoutMarginsGuide];
    [self.tableView.leadingAnchor constraintEqualToAnchor:margins.leadingAnchor] ;
    [self.tableView.trailingAnchor constraintEqualToAnchor:margins.trailingAnchor];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

    CGRect tableRect = self.view.frame;
    self.tableView.frame = tableRect;

    // table colors
    self.tableView.backgroundColor = [UIColor grayColor];
    self.tableView.separatorColor = [UIColor grayColor];
    UIView *backView = [[UIView alloc] init];
    [backView setBackgroundColor:[UIColor grayColor]];
    [self.tableView setBackgroundView:backView];
}

然后我设置单元格的内容:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor blueColor];
    cell.indentationWidth = 0;
    cell.indentationLevel = 0;
    cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);
    cell.contentView.backgroundColor = [UIColor purpleColor];
    return cell;
}

单元格背景是蓝色的,并且它横跨整个屏幕。 我的屏幕截图中紫色区域是 contentView,你可以看到,它不会延伸到屏幕右侧,而单元格文本在左侧缩进。 分隔符也在左右两侧缩进。

请按照我的答案操作,这可能有助于解决您的问题:http://stackoverflow.com/questions/34959397/how-do-i-make-the-uitableview-separator-inset-go-from-the-edges-of-the-screen/34959765#34959765 - technerd
谢谢@technerd!你的回答帮助我找到了我所缺少的东西。我将在下面的回答中发布详细信息。 - turnerjess
如果您发现我的回答有帮助,请点赞。谢谢。 - technerd
2个回答

4

感谢@technerd在我的问题下的评论,我才发现了这个问题。谢谢!

我在iOS 9.2上测试我的应用程序时,忽略了新的iOS9+单元格属性cellLayoutMarginsFollowReadableWidth,该属性会自动调整单元格布局。

要关闭自动调整大小功能,您需要检查iOS版本,然后禁用该属性,如@technerd所示:

Objective C

- (void)viewDidLoad {
    [super viewDidLoad];

    //For iOS 9 and Above 

    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 9.0) {
        self.tableView.cellLayoutMarginsFollowReadableWidth = NO;
    }
}

Swift

override func viewDidLoad() {
    super.viewDidLoad()

    //For iOS 9 and Above 
    if #available(iOS 9, *) {
        tableView.cellLayoutMarginsFollowReadableWidth = false
    }
}

希望这能帮助其他人。

2

上述解决方案不再完美地工作。尽管现在你所需要做的是:

Original Answer翻译成"最初的回答"

tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

这将使您的分隔符贯穿表视图的整个宽度。最初的回答。

太棒了!!谢谢。 - PhillipJacobs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接