这对我来说很好,而且我认为垂直
UIStackView
非常适合此类问题,而不是手动处理视图
class ViewController: UIViewController{
@IBOutlet var contentview: UIView!
@IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
contentview.backgroundColor = UIColor.lightGray
let vLayout = VerticalLayout(width: view.frame.width)
vLayout.backgroundColor = UIColor.cyan
contentview.addSubview(vLayout)
vLayout.addSubview(getView(color: UIColor.red))
vLayout.addSubview(getView(color: UIColor.magenta))
vLayout.addSubview(getView(color: UIColor.green))
vLayout.addSubview(getView(color: UIColor.blue))
vLayout.addSubview(getView(color: UIColor.yellow))
vLayout.addSubview(getView(color: UIColor.red))
vLayout.addSubview(getView(color: UIColor.magenta))
vLayout.addSubview(getView(color: UIColor.green))
vLayout.addSubview(getView(color: UIColor.blue))
vLayout.addSubview(getView(color: UIColor.yellow))
vLayout.addSubview(getView(color: UIColor.red))
vLayout.addSubview(getView(color: UIColor.magenta))
vLayout.addSubview(getView(color: UIColor.green))
vLayout.addSubview(getView(color: UIColor.blue))
vLayout.addSubview(getView(color: UIColor.yellow))
}
func getView(color:UIColor) -> UIView
{
let view = UIView(frame: CGRect(x:100, y:50, width:100, height:100))
view.backgroundColor = color
return view
}
}
class VerticalLayout: UIView {
var yOffsets: [CGFloat] = []
var heightValue : CGFloat = 0.0
init(width: CGFloat) {
super.init(frame: CGRect(x:0, y:0, width:width, height:0))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
var height: CGFloat = 0
for i in 0..<subviews.count {
let view = subviews[i] as UIView
view.layoutSubviews()
height += yOffsets[i]
view.frame.origin.y = height
height += view.frame.height
}
// main edit is here
self.frame.size.height = height
self.heightValue = height
let ff = self.superview
let dd = ff?.superview as! UIScrollView
dd.contentSize = CGSize.init(width: self.frame.size.width, height: height)
}
override func addSubview(_ view: UIView) {
yOffsets.append(view.frame.origin.y)
super.addSubview(view)
}
func removeAll() {
for view in subviews {
view.removeFromSuperview()
}
yOffsets.removeAll(keepingCapacity: false)
}
}