'Accessing Outlets from Different Files

I have a viewController with a bunch of labels. Each label has an outlet in that viewController.

I want the functions that operate on those labels to be in a different file. How do I access them?

Simplified example:

// File 1: VC1
class testScreen: UIViewController {

    @IBOutlet weak var myLabel: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()\
        
        formatLabel()
    }
}



// File 2: Functions

func formatLabel() {
    myLabel.backgroundColor = UIColor.green
}

(There are actually a lot of labels and fields and functions. I want to break everything up into small, manageable files.)



Solution 1:[1]

I'm not going to comment on the "best practices" to solve your organization problem, but according to your requirement, you would do this with extensions.

// File1.swift

class testScreen: UIViewController {

    @IBOutlet weak var myLabel: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()\
        
        formatLabel()
    }
}
// File2.swift

extension testScreen {
    func formatLabel() {
        myLabel.backgroundColor = UIColor.green
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric33187