create scrollview programmatically in swift without outlet
14,570
This is an answer from this question. .
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)
}
Author by
Muhammad Waqas
I have been developing mobile apps for 5 years. Worked in Objective-C and Swift programming languages.
Updated on June 14, 2022Comments
-
Muhammad Waqas almost 2 years
I have tried enough but i don't understand what is wrong with code, it was working fine when I created an outlet, but then I found out that i don't need an outlet, so want to create it just programmatically.
var BestPractices = UIScrollView(frame: CGRectMake(0, 94, 768, 924)) BestPractices.hidden = true
I cannot access the properties of "BestPractices" in viewController , while same code works fine in playground
-
mike vorisis over 7 yearsVery good answer! But I have one problem It returns me black background and i can't change it .