我应该如何设置自动布局约束,以便多线标签在scrollview中保持垂直居中,直到它的文本内容变得太长而无法立即显示?当文本长度变得太长时,文本应与滚动视图对齐,以便用户可以看到文本的开头并滚动查看更多内容。这就是我尝试设置约束的方法
for scrollView:
标签:
我还在viewDidLoad()
中添加了以下代码getName()
问题在于,但我仍然会收到一些警告,并且文字也会结束,并且#34;垂直居中"在scrollview内部,没有可能真正滚动到它的开头或结尾,即使它不能适合整个内部。对于scrollview,我得到警告,"具有不明确的可滚动内容宽度" ,而对于标签我得到警告"缺少尾随约束,这可能导致重叠与其他观点"
答案 0 :(得分:0)
如何将标签高度限制在scrollView
超级视图的高度?在这种情况下,label
将始终与显示它的屏幕一样大,并且由于默认情况下UILabel
中的文字是垂直居中的,因此您可以获得所需内容。请参阅以下Playgrounds示例以供参考:
import PlaygroundSupport
import UIKit
class A: UIViewController {
let scrollView = UIScrollView()
let label = UILabel()
override func viewDidLoad() {
self.view.backgroundColor = .white
self.view.addSubview(scrollView)
self.scrollView.addSubview(label)
label.numberOfLines = 0
label.text = "How should I setup auto layout constrains so that multiline label stays vertically centered inside scrollview until it's text content becomes too long to be shown at once?"
scrollView.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
scrollView.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor),
scrollView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor),
label.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor),
label.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor),
label.topAnchor.constraint(equalTo: self.scrollView.topAnchor),
label.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor),
label.heightAnchor.constraint(greaterThanOrEqualTo: self.view.heightAnchor),
])
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = A()