在 UITableViewCell 的子类中,我尝试使用自动布局。
这是我的代码,它不起作用:只显示一个 View
import Foundation
class CustomCell: UITableViewCell {
func configureCell() {
backgroundColor = UIColor.yellowColor()
let redColorView = UIView()
redColorView.backgroundColor = UIColor.redColor()
redColorView.translatesAutoresizingMaskIntoConstraints = false
let blueColorView = UIView()
blueColorView.backgroundColor = UIColor.blueColor()
blueColorView.translatesAutoresizingMaskIntoConstraints = false
addSubview(blueColorView)
addSubview(redColorView)
let viewsDictionary = ["blue":blueColorView,"red":redColorView]
let layout = NSLayoutFormatOptions(rawValue: 0)
let horizontalContraint:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("|-10-[blue]-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)
let verticalContraint_1:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[blue]-10-|", options: layout, metrics: nil, views: viewsDictionary)
let verticalContraint_2:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)
self.addConstraints(verticalContraint_1)
self.addConstraints(verticalContraint_2)
self.addConstraints(horizontalContraint)
}
}
最佳答案
问题是您的水平约束不明确。它们不足以解析为一种布局。因此,系统必须从各种可能性中任意选择。
特别是,|-10-[blue]-10-[red]-10-|
没有指定 blue
和 red< 的宽度
应该是。假设 superview 的宽度超过 30 个点,那么任何数量的解决方案都是可能的。 blue
可以是 0 宽度,red
可以是父 View 的宽度减去 30。反之亦然。或者介于两者之间的任何东西。对两个 subview 宽度的唯一有效约束是它们加起来等于父 View 的宽度减去 30。既然你说只有一个是可见的,那么可能另一个被分配了 0 宽度。
正如您所注意到的,您可以显式限制 subview 的宽度之一,或者您可以指定它们彼此具有相等的宽度(或其他比率)。
如果 View 具有固有大小,或者如果它们具有具有固有大小的 subview 并且它们的宽度基于它们的 subview 受到限制,那么诸如内容拥抱和抗压缩优先级之类的事情就会发挥作用。但是像您使用的普通 UIView
没有固有大小,所以它们没有。
关于ios - 水平自动布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34364872/