我找到了解决办法!
仅使用 Interface Builder 添加 UIScrollView 并添加约束以适应超级视图,并以编程方式创建所有子视图。
覆盖updateViewConstraints()并为 ScrollView 集合中的每个视图 translatesAutoresizingMaskIntoConstraints 为 false 并添加宽度约束以保持滚动视图宽度。不要忘记调用 super.updateViewConstraint()。
覆盖 didRotateFromInterfaceOrientation() 和 viewDidAppear() 并设置 scrollView.contentSize.height 以包装所有项目(如果不这样做,则无法滚动)。
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
var constraintsUpdated = false;
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.numberOfLines = 0
label.textColor = UIColor.blackColor()
scrollView.addSubview(label)
}
override func updateViewConstraints() {
if(constraintsUpdated){
//Rotate, just update view and keep constraints
super.updateViewConstraints()
scrollView.layoutSubviews()
return;
}
var viewsDictionary = ["label": label, "scrollView": scrollView]
let screenWidth = self.view.frame.width
label.setTranslatesAutoresizingMaskIntoConstraints(false)
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(String(format: "H:[label(==scrollView)]", screenWidth), options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary))
constraintsUpdated = true
super.updateViewConstraints()
//Update subviews
scrollView.layoutSubviews()
}
override func viewDidAppear(animated: Bool) {
scrollView.contentSize.height = label.bounds.height
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
scrollView.contentSize.height = label.bounds.height
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我找到了另一个使用 FLKAutoLayout 库的解决方案,用更少的代码就能很好地工作!
class ViewController: UIViewController {
var labelTitle: UILabel = UILabel()
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
//TITLE
scrollView.addSubview(labelTitle)
labelTitle.textColor = UIColor.blackColor()
labelTitle.numberOfLines = 0
//constraints
labelTitle.constrainWidthToView(self.view, predicate: nil)
labelTitle.numberOfLines = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
scrollView.contentSize.height = labelTitle.frame.height
}
}
不知道是 UIScrollView 有 AutoLayout 的 bug 还是某个特性