【问题标题】:When creating new tableView entry the constraints don't work创建新的 tableView 条目时,约束不起作用
【发布时间】:2015-06-12 10:58:07
【问题描述】:

我有一个使用 CoreData 的主从应用程序。一切都很好,并按预期工作。添加新条目时,显示只有一个问题。 左侧是 Master 的 TableView 和条目,右侧是 Detail 的 View,用户在其中输入新信息。

我有一个自定义的UITableViewCell 来处理格式。新条目的titleLabel 被约束正确定位。然而,detailTextLabel 似乎并不关心约束,它只是从单元格的左上角开始(所以在 0,0 位置),因此位于titleLabel 的顶部。

我做错了什么?

这是自定义 UITableViewCell 的自定义初始化程序:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    if (self) {

        self.backgroundColor = [UIColor darkGrayColor];
        self.textLabel.font = [Constants mainFontWithSize:16];
        self.detailTextLabel.font = [Constants mainFontWithSize:12];

        // correct default constraints
        self.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
        self.detailTextLabel.translatesAutoresizingMaskIntoConstraints = NO;

        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[textLabel]-35-|" options:0 metrics:nil views:@{ @"textLabel": self.textLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[detailTextLabel]-35-|" options:0 metrics:nil views:@{ @"detailTextLabel": self.detailTextLabel }]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-7-[textLabel(19)]-(3)-[detailTextLabel(14)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:@{ @"textLabel": self.textLabel, @"detailTextLabel": self.detailTextLabel }]];


    }
    return self;
}

谢谢

【问题讨论】:

    标签: uitableview ios8 nslayoutconstraint


    【解决方案1】:

    您似乎正在尝试为内置单元格样式的标签添加约束。

    这不起作用的原因是因为它们是(尚未公开的)内部标签,并且 Apple 的代码经过优化,可以在 Apple 认为不需要标签时从其 contentView 中删除其标签。

    当标签从其父视图中移除时,约束也会被移除。后来,当Apple给superView添加标签时,你添加的约束影响了内置的行为,所以它的标签现在放错了位置。

    要么让 Apple 自行管理和布局其内置的单元格样式,要么使用带有您自己的标签和约束的自定义单元格样式。

    【讨论】:

    • 完美运行。我认为可以覆盖默认标签上的约束。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 2018-12-30
    相关资源
    最近更新 更多