我已经以编程方式创建了一个堆栈视图,并添加了一个我已经以编程方式创建的视图。但是,当我尝试添加第二个视图时,它无法正常工作。 这是我的代码:
@IBOutlet weak var codingScrollView: UIView!
let codeStackView = UIStackView()
var codeViews = [CodeView]()
let codeView1 = CodeView(name: "Lennart", date: "13/05/2002", code: "Just some code")
let codeView2 = CodeView(name: "Nina", date: "01/07/1999", code: "Also some code")
codingScrollView是我添加到UIScrollView的内容视图。 codeStackView是我之前描述过的 codeViews数组用于将视图添加到stackview。
这里是viewDidLoad方法:
codeViews.append(codeView1)
codeViews.append(codeView2)
codingScrollView.addSubview(codeStackView)
codingScrollView.backgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1)
codeStackView.centerXAnchor.constraint(equalTo: codingScrollView.centerXAnchor)
codeStackView.centerYAnchor.constraint(equalTo: codingScrollView.centerYAnchor)
codeStackView.translatesAutoresizingMaskIntoConstraints = false
codeStackView.spacing = 10
codeStackView.axis = .horizontal
codeStackView.alignment = .center
for i in 0...codeViews.count - 1 {
codeStackView.addSubview(codeViews[i])
codeStackView.addArrangedSubview(codeViews[i])
}
但是,如果我运行应用程序它不会显示第二个视图,它只会显示其中一个。
非常感谢,非常感谢任何帮助
答案 0 :(得分:0)
首先尝试将codeView {1,2}添加到堆栈视图,然后将codeStackView
添加到codingScrollView
。
另外,在执行任何约束之前,请务必设置codeStackView.translatesAutoresizingMaskIntoConstraints = false
。
codeViews.append(codeView1)
codeViews.append(codeView2)
for i in 0...codeViews.count - 1 {
codeStackView.addSubview(codeViews[i])
codeStackView.addArrangedSubview(codeViews[i])
}
codeStackView.translatesAutoresizingMaskIntoConstraints = false
codeStackView.centerXAnchor.constraint(equalTo: codingScrollView.centerXAnchor)
codeStackView.centerYAnchor.constraint(equalTo: codingScrollView.centerYAnchor)
codeStackView.spacing = 10
codeStackView.axis = .horizontal
codeStackView.alignment = .center
codingScrollView.addSubview(codeStackView)
codingScrollView.backgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1)