无法设置通过 loadView 创建的 UIScrollView 的 contentSize [英] Cannot set contentSize of an UIScrollView created via loadView

查看:20
本文介绍了无法设置通过 loadView 创建的 UIScrollView 的 contentSize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 loadView 函数之外设置 UIScrollViewcontentSize.

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

但是,当我尝试这样做时,出现错误 'UIView' 没有名为 'contentSize' 的成员.

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

}

谢谢!

注意事项:

  • 在控制台中,view 确实是 UIScrollView 的一个实例,但是发送它 contentSize 给了我同样的错误.
  • self.view 替换 view 不能解决问题;这里没有局部变量干扰.
  • 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.

推荐答案

viewUIViewController 类型的 UIView 属性.因此,您应该先在局部变量中配置滚动视图,然后将其设置为视图变量:

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:

  • 为类添加新属性(良好做法)
  • 或者随时将 view 属性as UIScrollView 强制转换(非常糟糕的做法)
  • Add a new attribute to your class (good practice)
  • Or cast anytime the view attribute as UIScrollView (pretty bad practice)

例如:

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
    }

}

这篇关于无法设置通过 loadView 创建的 UIScrollView 的 contentSize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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