Swift:如何将 UIScrollView contentSize 高度设置为内容高度? [英] Swift: How to set UIScrollView contentSize height to height of contents?

查看:66
本文介绍了Swift:如何将 UIScrollView contentSize 高度设置为内容高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIScrollView.现在我只是将它设置为屏幕高度的两倍(在这种情况下,框架只是 UIScreen.mainScreen().bounds):

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)
  }
}

不过,我只希望它是里面所有内容的大小.我该怎么做?这是否意味着我必须在添加所有子视图后设置 contentSize?

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?

推荐答案

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

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

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

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.

这篇关于Swift:如何将 UIScrollView contentSize 高度设置为内容高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆