将 UILabel 固定到 UICollectionViewCell contentView 按钮的自动布局约束

Posted

技术标签:

【中文标题】将 UILabel 固定到 UICollectionViewCell contentView 按钮的自动布局约束【英文标题】:Autolayout Constraint to Pin UILabel to button of UICollectionViewCell contentView 【发布时间】:2013-06-26 18:47:39 【问题描述】:

我正在尝试使用可视化格式化语言向 UICollectionViewCell 子类添加一个简单的约束。我只想将 UILabel 固定到 contentView 的底部。这是我的初始化代码:

- (id)initWithFrame:(CGRect)frame 
    self = [super initWithFrame:frame];
    if(self) 
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 128, 50)];
        _label.font = [[UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline1] fontWithSize:20.0];
        _label.lineBreakMode = NSLineBreakByWordWrapping;
        _label.numberOfLines = 2;
       _label.contentMode = UIViewContentModeBottom;
       _label.backgroundColor = [UIColor blackColor];
       [self.contentView addSubview:_label];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_label]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_label)]];
    
    return self;

这是我在运行应用程序时收到的示例日志消息。

Unable to simultaneously satisfy constraints.
Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0xa3aa620 V:[UILabel:0xa3aa270]-(0)-|   (Names: '|':UIView:0xa3aa010 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x8b9b2d0 h=--& v=--& UILabel:0xa3aa270.midY == + 25>",
    "<NSAutoresizingMaskLayoutConstraint:0x8b9bba0 h=--& v=--& V:[UILabel:0xa3aa270(50)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x8bd1290 h=-&- v=-&- UIView:0xa3aa010.height == STStationGroupCollectionViewCell:0xa3a9f40.height>",
    "<NSAutoresizingMaskLayoutConstraint:0x8bb7ee0 h=--& v=--& V:[STStationGroupCollectionViewCell:0xa3a9f40(128)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0xa3aa620 V:[UILabel:0xa3aa270]-(0)-|   (Names: '|':UIView:0xa3aa010 )>

非常感谢任何帮助。谢谢!

【问题讨论】:

【参考方案1】:

尝试添加:

_label.translatesAutoresizingMaskIntoConstraints = NO;

似乎有一个自动调整大小约束试图修复标签的 midY。

【讨论】:

以上是关于将 UILabel 固定到 UICollectionViewCell contentView 按钮的自动布局约束的主要内容,如果未能解决你的问题,请参考以下文章

Xcode:将不同高度的 UILabel 限制为固定大小的容器

使用动态高度将视图固定到底部

自动布局和 UILabel 的问题

在固定的 UILabel 中处理长文本的最佳实践是啥

当 UITableViewCell 中的行数固定时,UILabel 占用空间?

在 UIImageView 上设置顶部约束会导致 UILabel 固定高度