I created a scroll view in story board. I added UIlabel programmatically inside the scrollView. I set the right anchor of that UiLabel to right anchor of the scroll view, but it seem not working right.
What the problem or I'm missing somethings. Please help
Here the a part of my code
@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
}
}
Here is the constraint of scroll view
Here is what I got (I don't want it can horizontal scroll)

Here is something what I want

Sorry because of my bad english
I think this is because you didn't define a width constraint for the meaningLabel, so the scroll view keeps scrolling horizontally based on the length of text that label displays.
The text should be wrapped once you define that constraint (assuming meaningLabel.numberOfLines is set to 0):
meaningLabel.widthAnchor.constraint(equalTo: self.scrollView.widthAnchor, constant: -16).isActive = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With