我还是SO和Swift的新手,所以请耐心:-)
我有一个UIViewController
。
在此viewcontroller
内有一个UIScrollView
。
在UIScrollView
内有一个UIStackView
(用AutoLayout
固定在0,0,0,0,垂直和水平居中),水平轴。
我的目标是向堆栈视图添加子视图,并使滚动视图水平滚动。
所以,我做了以下事情:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scroller: UIScrollView!
@IBOutlet weak var stack: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
scroller.delegate = self
for i in 0..<10 {
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
// .random is unimportant here
customView.backgroundColor = .random()
stack.addArrangedSubview(customView)
}
}
override func viewDidLayoutSubviews(){
self.scroller.contentSize = CGSize(width:2400,height:128)
print(self.scroller.contentSize) // 2400
print(self.stack.subviews)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("scrollin'")
}
}
问题是我必须缺少某些东西,因为scrollview根本无法滚动。我只能看到一个视图(当然,随时可以使用不同的颜色)。
我确定视图已加载,因为这是第二个打印输出:
[<UIView: 0x159e01a10; frame = (0 0; 240 128); layer = <CALayer: 0x28115d7a0>>, <UIView: 0x159e03f10; frame = (0 0; 240 128); layer = <CALayer: 0x28115d800>>, <UIView: 0x159e046d0; frame = (0 0; 240 128); layer = <CALayer: 0x28115d960>>, <UIView: 0x159e0e410; frame = (0 0; 240 128); layer = <CALayer: 0x28115da80>>, <UIView: 0x159e0e7c0; frame = (0 0; 240 128); layer = <CALayer: 0x28115db20>>, <UIView: 0x159e0e9a0; frame = (0 0; 240 128); layer = <CALayer: 0x28115da60>>, <UIView: 0x159e0eb80; frame = (0 0; 240 128); layer = <CALayer: 0x28115dbe0>>, <UIView: 0x159e0ed60; frame = (0 0; 240 128); layer = <CALayer: 0x28115dc80>>, <UIView: 0x159e0ef40; frame = (0 0; 240 128); layer = <CALayer: 0x28115dd20>>, <UIView: 0x159e0f120; frame = (0 0; 240 128); layer = <CALayer: 0x28115ddc0>>]
那么,这是怎么回事?为什么滚动视图不滚动?
答案 0 :(得分:-1)
替换此
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 240, height: 128))
使用
let customView = UIView(frame: CGRect(x: CGFloat( i * 240 ) , y: 0, width: 240, height: 128))
我认为不需要stackView,并且
scroller.addSubview(customView)
查看此Scroller
答案 1 :(得分:-1)
尝试此代码,希望对您有所帮助。
override func viewDidLoad() {
super.viewDidLoad()
scroller.delegate = self
for i in 0..<10 {
let xPosition = 240 * CGFloat(i)
let customView = UIView(frame: CGRect(x: xPosition, y: 0, width: 240, height: 128))
// .random is unimportant here
customView.backgroundColor = .random()
scroller.addSubview(customView)
}
scroller.contentSize.width = 2400
}