Tung Vu Duc
Tung Vu Duc

Reputation: 1662

I can't add subViews in UIScrollView

I'm trying add a subview to UIScrollView. I add scrollView, subView and set constraints bellow :

class ViewController: UIViewController {

let scrollView : UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.backgroundColor = .yellow
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.alwaysBounceVertical = true
    return scrollView
}()

let catImageView : UIImageView = {
    let img = UIImageView()
    img.translatesAutoresizingMaskIntoConstraints = false
    img.backgroundColor = .white
    return img
}()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .black

    view.addSubview(scrollView)
    scrollView.frame = self.view.bounds
    scrollView.contentSize = CGSize(width: self.view.frame.width, height: 1000)

    scrollView.addSubview(catImageView)
    catImageView.centerXAnchor.constraint(equalTo: self.scrollView.centerXAnchor).isActive = true
    catImageView.centerYAnchor.constraint(equalTo: self.scrollView.centerYAnchor).isActive = true
    catImageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    catImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
 }

I builded and scrollView and subiew are disappear. I don't know why... Then I trying add subview another way like this :

        view.addSubview(catImageView)
    catImageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    catImageView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    catImageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    catImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true

It's still the same. Please explained to me why. Thank a lot

Upvotes: 1

Views: 816

Answers (1)

timaktimak
timaktimak

Reputation: 1380

You should only set the translatesAutoresizingMaskIntoConstraints to false in case you are adding the constraints to the view. You've set the property on the scrollView to false, but used the frame, and not constraints. Remove the line:

scrollView.translatesAutoresizingMaskIntoConstraints = false // <- remove

and it should work.

Hope this helps! Good luck!

Upvotes: 2

Related Questions