6

我正在以编程方式设置 UITableView。我希望单元格的内容跨越屏幕的整个宽度。我已经成功地将单元格设置为跨越屏幕的宽度,但内容和分隔符仍然显着插入(下面的 iPad 屏幕截图)。

这是我的视图控制器实现中的 tableview 布局设置:

- (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,如你所见,它没有延伸到屏幕的右边缘,并且单元格文本在左侧插入。分隔符也插入在左右两侧。

表格截图

4

2 回答 2

4

由于@technerd 对我的问题的评论,我发现了这个问题。谢谢!

我在 iOS 9.2 上测试我的应用程序,但我忽略了新的 iOS9+ 单元格属性cellLayoutMarginsFollowReadableWidth,它默认调整单元格布局。

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

目标 C

- (void)viewDidLoad {
    [super viewDidLoad];

    //For iOS 9 and Above 

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

迅速

override func viewDidLoad() {
    super.viewDidLoad()

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

希望这对其他人有帮助。

于 2016-01-29T18:42:26.623 回答
2

上述解决方案实际上不再完美。虽然,您现在需要做的就是:

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

这将使您的分隔符贯穿整个表格视图的宽度。

于 2019-07-15T10:47:04.250 回答