Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to set UIScrollView contentSize height to height of contents?

I have a UIScrollView. Right now I am just setting it to double the height of the screen (frame in this case is just UIScreen.mainScreen().bounds):

class VenueDetailView: UIScrollView {
  required init?(coder aDecoder: NSCoder) { fatalError("Storyboard makes me sad.") }

  override init(frame: CGRect) {
    super.init(frame: frame)
    contentSize = CGSize(width: frame.width, height: frame.height*2) <----------------

    backgroundColor = UIColor.greenColor()
  }


  func addBannerImage(imageUrl: NSURL) {
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 300))

    // TODO: Make this asynchronous
    // Nice to have: cache the image
    if let data = NSData(contentsOfURL: imageUrl) {
      imageView.image = UIImage(data: data)
    }

    addSubview(imageView)
  }
}

However, I just want it to be the size of all the contents inside it. How would I do this? Does this mean I have to set the contentSize after I add all the subviews?

like image 900
bigpotato Avatar asked Nov 15 '15 01:11

bigpotato


1 Answers

Does this mean I have to set the contentSize after I add all the subviews?

Basically yes. Your goal should be to make the scroll view small and the content size big. That is what makes a scroll view scrollable: its contentSize is bigger than its own bounds size. So, set the scroll view itself to have a frame that is the same as the bounds of its superview, but then set its contentSize to embrace all its subviews.

like image 111
matt Avatar answered Nov 17 '22 21:11

matt