(斯威夫特)ScrollView 中的 StackView 不起作用



我想在scrollView中创建一个stackView。
在stackView,我想添加一些其他的stackView,但它没有工作。

因此,为了简化,我添加了一些UIViews与addArrangedSubview()但它不显示任何东西。
我该如何解决这个问题?我花了很多时间……

scrollView = UIScrollView()
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor),
scrollView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor),
scrollView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
scrollView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])


var line1 = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 1000))
line1.backgroundColor = .blue
var line2 = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 1000))
line2.backgroundColor = .green


profile()

stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
scrollView.addSubview(stackView)


stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
])

stackView.addArrangedSubview(line1)
stackView.addArrangedSubview(line2)

stackView.updateConstraints()
stackView.setNeedsLayout()

我猜此刻这段代码正在运行,ViewControllers - view仍然没有设置,所以你的line1/2的宽度将导致0。你也应该使用auto layout来布局你的视图。

var line1 = UIView()
line1.translatesAutoresizingMaskIntoConstraints = false 
line1.backgroundColor = .blue
var line2 = UIView()
line1.translatesAutoresizingMaskIntoConstraints = false 
line2.backgroundColor = .green

stackView = UIStackView(arrangedSubviews: [line1, line2])
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
line1.widthAnchor.constraint(equalTo: view.widthAnchor),
line1.heightAnchor.constraint(equalToConstant: 1000),
line2.widthAnchor.constraint(equalTo: view.widthAnchor),
line2.heightAnchor.constraint(equalToConstant: 1000),
])

相关内容

  • 没有找到相关文章

最新更新