johnson lai
johnson lai

Reputation: 1036

How to call a function that is located in another class in Swift?

I try to make the Label in iOS app to show "asdf" in label using 2 view controller.

I try to run testA() function but it shows out an error: ViewController.swift:15:9: Use of unresolved identifier 'testA'

My initial code:

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        testA()
    } 
}
In another controller (TestViewController):
import UIKit

class TestViewController: UIViewController {
    @IBOutlet weak var testLabel: UILabel!

    func testA() {
        testLabel.text = "asdf"
    }

}

and my Main.storyboard is linked to TestViewController class

I did a little bit search on google and I came to try out inheritance and It did not shows the error, but the function was not called.

I try to use Inheritance method:

In View Controller (ViewController.swift):
import UIKit

class ViewController: TestViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        testA()
    }
}

The error was resolved, but the label did not change to asdf

How do I make my ViewController.swift able to call the function testA() that is located in another controller TestViewController.swift ?

Upvotes: 3

Views: 10841

Answers (3)

Parth Adroja
Parth Adroja

Reputation: 13514

You can create an object of that class and you can call the function as below.

let testVC = TestViewController()

Now call the function using the object

testVC.testA()

Or better approach is to create a class func if you want to call it from many places and it's independent of the object.

class Helper {
    class func testFunction() {
      // Do something
    }
}

In above scenario, you don't have to create the object as it's a class method so call it like below.

Helper.testFunction()

Upvotes: 4

Henson Fang
Henson Fang

Reputation: 1207

public the testA() function and call the

TestViewController.testA() 

in the override func viewDidLoad()of ViewController import TestViewController at first.

Upvotes: 1

Maximo Lucosi
Maximo Lucosi

Reputation: 166

You can use NSNotification or ou can use delegate if load the second view after the first.

Upvotes: 2

Related Questions