Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel right anchor not working with scroll view swift

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

like image 450
user3783161 Avatar asked Nov 16 '25 15:11

user3783161


1 Answers

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
like image 200
Ozgur Vatansever Avatar answered Nov 18 '25 07:11

Ozgur Vatansever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!