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

我有一个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) } } 

不过,我只是希望它是它里面所有内容的大小。 我将如何做到这一点? 这是否意味着我必须在添加所有子视图后设置contentSize

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

基本上是的。 你的目标应该是使滚动视图小,内容大小。 这就是滚动视图可滚动的原因:它的contentSize大于它自己的边界大小。 所以,设置滚动视图本身有一个frame是相同的超监视的bounds ,但是然后设置它的contentSize包含所有的子视图。