我在 Storyboard中创建了一个 ScrollView 。我在 scrollView 中以编程方式添加了 UIlabel。我将该 UiLabel 的右 anchor 设置为 ScrollView 的右 anchor ,但它似乎无法正常工作。
有什么问题,或者我遗漏了什么。请帮忙
这是我的代码的一部分
@IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
var lastBottomAnchor = self.scrollView.topAnchor
for vocab in self.vocabularies {
// Index
let indexLabel = UILabel()
indexLabel.text = vocab["index"] as? String
indexLabel.font = UIFont.systemFont(ofSize: 14)
indexLabel.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.addSubview(indexLabel)
indexLabel.topAnchor.constraint(equalTo: lastBottomAnchor).isActive = true
indexLabel.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor, constant: 8).isActive = true
indexLabel.widthAnchor.constraint(equalToConstant: 40).isActive = true
// Meaning
let meaningLabel = UILabel()
meaningLabel.text = "意味:\(vocab["english"]!)/\(vocab["vietnamese"]!)"
meaningLabel.numberOfLines = 0
meaningLabel.font = UIFont.systemFont(ofSize: 12)
meaningLabel.layer.borderWidth = 0
meaningLabel.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.addSubview(meaningLabel)
meaningLabel.topAnchor.constraint(equalTo: indexLabel.bottomAnchor, constant: 8).isActive = true
meaningLabel.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor, constant: 8).isActive = true
meaningLabel.rightAnchor.constraint(equalTo: self.scrollView.rightAnchor, constant: -8).isActive = true
// Set last item bottom constraint
lastBottomAnchor = meaningLabel.bottomAnchor
}
}
这里是 ScrollView 的约束 这是我得到的(我不希望它可以水平滚动)
对不起,因为我的英语不好
最佳答案
我认为这是因为您没有为 meaningLabel
定义宽度限制,所以 ScrollView 会根据标签显示的文本长度水平滚动。
一旦定义了该约束,文本就应该换行(假设 meaningLabel.numberOfLines
设置为 0
):
meaningLabel.widthAnchor.constraint(equalTo: self.scrollView.widthAnchor, constant: -16).isActive = true
关于ios - UILabel 右 anchor 不适用于 ScrollView swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737739/