Cannot set contentSize of an UIScrollView created via loadView

不羁岁月 提交于 2019-12-11 21:13:09

问题


I need to set the contentSize of an UIScrollView outside of the loadView function.

However when trying to do so, I have the error 'UIView' does not have a member named 'contentSize'.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        var bigRect = view.bounds
        bigRect.size.width *= CGFloat(someInt)

        view.contentSize = bigRect // 'UIView' does not have a member named 'contentSize'
    }

    override func loadView() {
        view = UIScrollView(frame: UIScreen.mainScreen().bounds)
    }

}

Thanks !

Notes:

  • in the console, view is indeed an instance of UIScrollView but sending it contentSize gives me the same error.
  • replacing view by self.view doesn't solve the issue ; there is no local variable interfering here.

回答1:


view is an UIViewController attribute of type UIView. So you should configure the scroll view within a local variable first and then set it to the view variable :

override func loadView() {
    var scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
    scrollView.contentSize = <Whatever>
    view = scrollView
}

If you plan to change the scroll view later you should consider either:

  • Add a new attribute to your class (good practice)
  • Or cast anytime the view attribute as UIScrollView (pretty bad practice)

E.g:

class ViewController: UIViewController {
    var scrollView:UIScrollView!

    override func viewDidLoad() {
        var bigRect = view.bounds
        bigRect.size.width *= CGFloat(someInt)

        scrollView.contentSize = bigRect.size
    }

    override func loadView() {
        scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
        view = scrollView
    }

}



回答2:


Try renaming it to scrollView instead of view as view is already a variable attached to all UIViewControllers so it might be getting confused. Unless of course you are trying to say that you replaced the view with a scrollView in the storyboard. In this case, you need to cast the view as a scrollView as shown below:

(view as UIScrollView).contentSize


来源:https://stackoverflow.com/questions/25814458/cannot-set-contentsize-of-an-uiscrollview-created-via-loadview

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