3
votes

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 enter image description here Here is what I got (I don't want it can horizontal scroll) enter image description here

Here is something what I want enter image description here

Sorry because of my bad english

2

2 Answers

1
votes

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
0
votes

You could lock the horizontal scrolling, limiting the scroll view's content size, doing so:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.scrollView.contentSize = self.view.frame.size
}