Kevin T
Kevin T

Reputation: 303

How to access a scroll view sub class from the main view controller (Beginner)

Using swift 3, I have a UIScrollView in my main view. I call it my "feature scroll view"

I have also added a custom class to my UIScrollView, which has one function in it called loadFeatures()

featureScrollView.swift:

class featureScrollView: UIScrollView {

public func loadFeatures () {
    //Add Pictures to the UIScrollView
}

How do i call loadFeatures() on the UIScrollView instance that exists from my ViewController.swift class in my main view?

In my ViewController.swift I want to simply write

scrollView.loadFeatures() 

and have the code in loadFeatures() apply to the scrollView that is currently on the screen. I am beginning learning Swift and I appreciate everybody's help greatly!

image of ScrollView and corresponding class

Upvotes: 1

Views: 740

Answers (2)

Abhijit
Abhijit

Reputation: 173

Bind the IBOutlet of scrollview (Scrollview that you have shown in https://i.sstatic.net/5HRH0.png) in your ViewController.swift and just call loadFeatures() from ViewController.swift with that outlet instace.

ex., once you bind outlet like as below

class ViewController: UIViewController {

@IBOutlet weak var scrollView: featureScrollView!

override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.loadFeatures()
   }

}

Upvotes: 3

Zonily Jame
Zonily Jame

Reputation: 5349

Since you've already made a custom class for your ScrollView you could easily access that by subclassing your scrollView in your *.storyboard

For example:

You could set the custom class of your scrollView by placing it in here

enter image description here

Which would look like this

enter image description here

Note: This is just one way of doing things

Another is to do it manually inside your UIViewController class like this

class ViewController: UIViewController {

    var ftScrollView: FeatureScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        ftScrollView = FeatureScrollView()  // I Initialized the scrollView
        ftScrollView.frame = // some frame here
        view.addSubView(ftScrollView)
        ftScrollView.loadFeatures()

    }
}

PS: Please conform to swift coding standards. You should always start class names with a capital letter, thus this class featureScrollView: UIScrollView should be named like this class FeatureScrollView: UIScrollView

Upvotes: 1

Related Questions