Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using snapkit / autolayout with UIScrollView

I have an app that will have a

  • scrollView
    • contentView
      • chart
      • buttons
      • other stuff

I tried constraining it like shown below, but I am missing a constraint and I can't find out what I need.

    self.view.addSubview(self.scrollView)
    self.scrollView.snp.makeConstraints { (make) in
        make.edges.equalTo(self.view)
    }
    let contentView = UIView()

    self.scrollView.addSubview(contentView)
    contentView.snp.makeConstraints { (make) in
        make.top.bottom.equalTo(self.scrollView)
        make.left.right.equalTo(self.view)
    }
    contentView.addSubview(self.chart)
    self.chart.snp.makeConstraints { (make) in
        // http://snapkit.io/docs/
        make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 30, left: 0, bottom: 50, right: 0))
    }

where scrollView = UIScrollView()

like image 218
Peter S Avatar asked Oct 17 '18 13:10

Peter S


2 Answers

You need to add width/height or alignment constraints for contentView. Try this:

contentView.snp.makeConstraints { (make) in
    make.top.bottom.equalTo(self.scrollView)
    make.left.right.equalTo(self.view)
    make.width.equalTo(self.scrollView)
    make.height.equalTo(self.scrollView)
    // or:
    // make.centerX.equalTo(self.scrollView)
    // make.centerY.equalTo(self.scrollView)
}
like image 146
Ilya Kharabet Avatar answered Nov 09 '22 14:11

Ilya Kharabet


@Ilya Kharabet's answer for short:

contentView.snp.makeConstraints { (make) in
    make.left.right.equalTo(self.view)
    make.width.height.top.bottom.equalTo(self.scrollView)
}

PS:

ususally we use make.leading.trailing, instead of make.left.right, for RTL Support .

like image 2
dengST30 Avatar answered Nov 09 '22 13:11

dengST30