Swift:如何将UIScrollView contentSize高度设置为内容高度?

big*_*ato 5 uiscrollview ios swift

我有一个UIScrollView.现在我只是将它设置为加倍屏幕的高度(在这种情况下框架只是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)
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我只想让它成为其中所有内容的大小.我该怎么做?这是否意味着我必须contentSize在添加所有子视图后设置?

mat*_*att 9

这是否意味着我必须在添加所有子视图后设置contentSize?

基本上是的.您的目标应该是使滚动视图变小,内容大小变大.这就是滚动视图可滚动的原因:它contentSize比它自己的边界大小更大.因此,将滚动视图本身设置为与其超级视图frame相同bounds,但是将其设置contentSize为包含其所有子视图.

  • 我如何找到uiscrollview的所有子视图的总高度? (3认同)