iOS 8和layoutMargin中的自定义UITableViewCells

问题描述 投票:11回答:4

我的应用程序中有几个自定义UITableViewCells,主要由nibs定义。移动到iOS 8和Xcode 6时,左右边距不正确。这些单元格通常散布在具有默认单元格的表格视图中。

我做了一个示例项目,这是我正在谈论的保证金问题:

我能找到的唯一与此相关的是新物业layoutMargins。对于UITableViewCells,其值似乎会根据运行应用程序的设备而改变:

iPhone 6 and below - layoutMargin: {8, 16, 8, 16}
iPhone 6 Plus - layoutMargin: {8, 20, 8, 20}

这似乎与我在标准单元格上看到的边缘对齐。但是,我的自定义单元格的内容位于单元格contentView内,后者具有layoutMargin的标准UIView {8, 8, 8, 8}。这意味着绑定到Container Margin的任何自动布局约束都会添加不正确的间距。

我发现解决这个问题的唯一方法是在cellForRowAtIndexPath:中添加以下内容

cell.contentView.layoutMargins = cell.layoutMargins;

这似乎不是一个非常好的解决方案(特别是因为我需要将它包装在iOS8的支票中以保持兼容性)。

有没有人有任何想法?我觉得我必须遗漏一些东西。

objective-c uitableview ios8
4个回答
14
投票

您可能想要查看preservesSuperviewLayoutMargins属性。这听起来像你在寻找。

将以下内容添加到需要与标准单元格保持一致的任何单元格中:

- (void)layoutSubviews {
    [super layoutSubviews];

    if ([self.contentView respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        self.contentView.preservesSuperviewLayoutMargins = YES;
    }
}

5
投票

在你的UITableViewCell子类中,覆盖layoutMarginsDidChange并设置contentView的layoutMargins以匹配单元格的layoutMargins:

- (void)layoutMarginsDidChange {
    contentView.layoutMargins = layoutMargins
}

我发现这比将preservesSuperviewLayoutMargins设置为YES更可靠。


0
投票

preservesSuperviewLayoutMargins为iOS8解决了这个问题。下面的代码包括,以及为ios7.1解决它的其他代码。

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var mainLabel: UILabel!

    override func layoutSubviews() {
        super.layoutSubviews()

        if contentView.respondsToSelector(Selector("preservesSuperviewLayoutMargins")) {
            contentView.preservesSuperviewLayoutMargins = true
        } else {
            if mainLabel != nil {
                let leftConstraint = NSLayoutConstraint(item: mainLabel,
                    attribute: .Leading,
                    relatedBy: .Equal,
                    toItem: contentView,
                    attribute: .Leading,
                    multiplier: 1.0,
                    constant: 16.0);
                addConstraint(leftConstraint);
            }
        }
    }

}

0
投票

要在表格视图中删除iOS 8+中那个时髦的左边距:

table.separatorInset = UIEdgeInsets.zero     // or UIEdgeInsetsZero

您可能还需要:

table.layoutMargins = UIEdgeInsets.zero

感谢https://stackoverflow.com/a/30640595/385273

© www.soinside.com 2019 - 2024. All rights reserved.