Search code examples
swiftiboutlet

UILabel in function in separate swift file


I was wondering how to use a UILabel

@IBOutlet weak var MyLabel : UILabel!

in a function, in another swift file.

"SecondSwift file"

func MyFunc {
print(MyLabel.text = "")
}

Now I've got the problem that i can't use my UILabel in a separate swift file

I've got a lot of functions and my MainViewController gets chaotic if i need to make all my functions there.

So i was wondering if its possible to use a UILabel in a function in another swift file so i can use it later on


Solution

  • If the purpose is to simply split up the source code related to MainViewController to more than one source file, you can create an extension to your class MainViewController in a separate .swift source file.

    Consider the following simple example, consisting of two source files, MainViewController.swift and MainViewControllerExtensions.swift:

    /* Source file: MainViewController.swift */
    import UIKit
    
    class MainViewController: UIViewController {
    
        @IBOutlet weak var myLabel: UILabel!
        private var myPrivateInt = 1
    
        // ...
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            myLabel.text = "foo"
    
            /* member methods defined in separate source file      */
            foo()               /* set 'myLabel' text to "foobar"  */
            printLabel(myLabel) /* print text of UILabel argument; 
                                   here, prints "foobar"           */
        }
    }
    
    /* Source file: MainViewControllerExtensions.swift */
    extension MainViewController {
    
        func foo() {
            myLabel.text = "foobar"
            // myPrivateInt <-- not accessible in this scope
        }
    
        func printLabel(label: UILabel) {
            print(label.text ?? "")
        }
    }
    

    After the view has been loaded in the simple example above, your label will have text "foobar".

    Note however that extensions in separate source files cannot access private properties and methods from the main file. Most entities in swift, have, however, a default access level of internal; you can access internal properties and methods from a separate source file, as shown in the example above. So unless you explicitly define private access level for properties/methods, you will be able to access them in the separate-source-file extension.

    For more information regarding access levels in Swift, please refer to the Language Guide - Access Control.