无需插座即可快速以编程方式创建滚动视图

Muh*_*qas 2 uiscrollview swift

我已经尝试了足够多,但我不明白代码有什么问题,当我创建一个插座时它工作正常,但后来我发现我不需要一个插座,所以想以编程方式创建它。

var BestPractices = UIScrollView(frame: CGRectMake(0, 94, 768, 924))
BestPractices.hidden = true
Run Code Online (Sandbox Code Playgroud)

我无法访问 viewController 中“BestPractices”的属性,而相同的代码在操场上运行良好

atw*_*lsh 5

这是来自这个问题的答案。.

class ScrollingViewController : UIViewController {
// Create a scrollView property that we'll set as our view in -loadView
let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)

override func loadView() {
    // calling self.view later on will return a UIView!, but we can simply call 
    // self.scrollView to adjust properties of the scroll view:
    self.view = self.scrollView

    // setup the scroll view
    self.scrollView.contentSize = CGSize(width:1234, height: 5678)
    // etc...
}

func example() {
    let sampleSubView = UIView()
    self.view.addSubview(sampleSubView) // adds to the scroll view

    // cannot do this:
    // self.view.contentOffset = CGPoint(x: 10, y: 20)
    // so instead we do this:
    self.scrollView.contentOffset = CGPoint(x: 10, y: 20)
}
Run Code Online (Sandbox Code Playgroud)