我尝试以编程方式将视图添加到UIScrollView,以便在调整子视图大小时,UIScrollView contentSize将自动匹配。
我试过这个:
private var _contentView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
addSubview(_contentView)
let leading = NSLayoutConstraint(item: _contentView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: _contentView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: _contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: _contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.addConstraints([leading,trailing,top,bottom])
但是我在运行时遇到一个关于无法满足约束的错误。
我也尝试使用可视格式设置约束并得到类似的错误:
let viewsDictionary = ["contentView":_contentView]
let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[contentView]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: viewsDictionary)
let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[contentView]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: viewsDictionary)
self.addConstraints(hConstraints)
self.addConstraints(vConstraints)
如何正确添加约束?
答案 0 :(得分:0)
尝试在内容视图中将translatesAutoresizingMaskIntoConstraints
设置为NO / false。
如果是滚动视图,子视图需要具有内在内容大小或显式宽度和高度约束,以允许滚动视图确定其内容大小。
因此,请尝试在内容视图中添加宽度和高度限制。