【发布时间】:2017-05-19 13:25:00
【问题描述】:
我想在 scrollview 中水平创建 N 个视图。所以我创建了一个 Temporary View 并将 current view 分配给它。然后我根据它放置约束。只有一个视图显示其他视图未显示。 我想要两个视图之间的水平空间。 我正在使用 VFL 设置自动布局。 这是我尝试的代码。
func ect() {
let scrollHeight = self.scrollObj.frame.size.height - 40
let scrollHeightString = String(describing: scrollHeight)
print(scrollHeightString)
var firstTextView = UIView() // this is temporary view
var columnIndex: CGFloat = 0
for _ in 0 ..< 5 {
let textViewSample = UITextView()
textViewSample.translatesAutoresizingMaskIntoConstraints = false
//textViewSample.attributedText = self.htmlString.utf8Data?.attributedString
textViewSample.isScrollEnabled = false
textViewSample.tag = Int(columnIndex)
textViewSample.backgroundColor = UIColor.green
self.scrollObj.addSubview(textViewSample)
if columnIndex == 0{
//here i am setting first view to left margin.
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textViewSample]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample]))
//height to textview
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[textViewSample(200)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample]))
//width to textview
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[textViewSample(200)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample]))
}else{
//setting horizontal space to Temp view and current view
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[firstTextView]-(10)-[textViewSample]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample,"firstTextView":firstTextView]))
//setting equal width and equal height to second textview based on first
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[firstTextView][textViewSample(==firstTextView)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample,"firstTextView":firstTextView]))
}
//y position to textview
self.scrollObj.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(20)-[textViewSample]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["textViewSample":textViewSample]))
firstTextView = textViewSample//assigning current view to temp view.
// Increase the current offset
columnIndex = columnIndex + 1
}
self.scrollObj.contentSize = CGSize(width: columnIndex*200, height: columnIndex*200)
self.scrollObj .setNeedsLayout()
self.scrollObj.layoutIfNeeded()
}
这就是我的设计:-
【问题讨论】:
-
尽可能使用 UIStackView
-
我需要放置一个动态视图,我没有堆栈视图的经验,这就是我想要的。
标签: ios ipad autolayout swift3