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

こ雲淡風輕ζ 提交于 2019-12-22 06:25:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33715402/swift-how-to-set-uiscrollview-contentsize-height-to-height-of-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!