[英]UICollectionView Cell + UiLabel with AutoLayout
我正在尝试将UILabel固定到它的父细胞上。 我添加了四个约束(顶部,前导,尾随,底部) ,它们在iOS 8.0上运行良好,但在iOS 7.X上运行不正常 。 请看下面的图片:
我究竟做错了什么? 请指教!
它似乎只是在Xcode 6 GM之后才被打破。 我的方法在Xcode 6 beta 7中运行良好。
此外,如果我减少内部视图的宽度,它会抛出以下警告:
2014-09-10 19:58:28.109 Test[57827:60b] 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:0x799573a0 H:|-(8)-[UIView:0x798a86e0] (Names: '|':UIView:0x798ae5d0 )>",
"<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-| (Names: '|':UIView:0x798ae5d0 )>",
"<NSAutoresizingMaskLayoutConstraint:0x798a8b00 h=--& v=--& H:[UIView:0x798ae5d0(50)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-| (Names: '|':UIView:0x798ae5d0 )>
Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
覆盖自定义单元格的layoutSubviews
是一种可能的解决方法:
override func layoutSubviews() {
contentView.frame = bounds
super.layoutSubviews()
}
UIView:0x798ae5d0是CollectionViewCell的contentView。 不知何故,它在某个时刻使用UICollectionViewCells defaultSize,即(50.0,50.0)。
<NSAutoresizingMaskLayoutConstraint:0x798a8b00 h=--& v=--& H:[UIView:0x798ae5d0(50)]>
由于水平边距8 + 43 = 51大于contentView(50),因此无法满足布局。
<NSLayoutConstraint:0x799573a0 H:|-(8)-[UIView:0x798a86e0] (Names: '|':UIView:0x798ae5d0 )>
<NSLayoutConstraint:0x799573d0 H:[UIView:0x798a86e0]-(43)-| (Names: '|':UIView:0x798ae5d0 )>
可以使布局更灵活,因此它也适用于(50.0,50.0)尺寸。 在您的情况下,通过将等于43更改为<= 43或通过将优先级降低到1000到750或999。
问题是您的自定义视图(UILabel)具有约束,这些约束与单元格(或更好的单元格的contentView)约束冲突。 单元格的NSAutoresizingMaskLayoutConstraint是根据您在xib(或storyboard)中的UICollectionView属性中设置的单元格大小自动创建的。 我通过明确设置解决了我的类似问题(*)
- (void)awakeFromNib {
[super awakeFromNib];
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
}
在我的自定义UICollectionViewCell子类中。 这摆脱了Storyboard中设置的单元格大小约束。
(*)免责声明:我的collectionView具有基于其内容视图的自定义单元格,该内容视图由autolayout定义。 我有关于内容自动布局的冲突约束和Storyboard中的显式大小的警告。 这帮助我摆脱了那些警告。
而不是给出四个约束(顶部,前导,尾随,底部)。 尝试顶部,前导,宽度和高度。 它应该工作。
我希望你已经为它的父级(它将是UIViewController的视图)添加了对集合的约束,因此它的宽度和高度等于父视图。
我在项目中找到的另一种可能性。
通常我会复制/粘贴类似的对象,但有时这样做会保留相同的ID。
所以我通过从头创建一个对象来修复我的约束问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.