2

I have a view controller which has a programmatically created label like below.

class MyController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        setupUI()
    }

    func setupUI() {
       // added an setup the view constraints.
    }
}

This works properly. Then I tried to move all the UI element of the view controller to it's extension by creating a extension like below :

private extension MyController {

    var label: UILabel = {
      **// tried to initialize the label like this. but getting cannot use stored property in extension error**
    }()

// then tried like below
    var mylabel: UILabel! {
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = "Hello"
            return label
        }

     func setupUI() {
        // with the second option I getting nil value error.
        }
}

How can I initialize UI elements in viewcontroller extentions programmatically to access internally.

Marlon Brando aka Ben
  • 863
  • 1
  • 14
  • 33

2 Answers2

1

Try this:

uielements.swift

extension MyController {
    static let myLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Hello"
        return label
    }()
}

myController.swift

class MyController: UIViewController {

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

    private func setupUI() {
        view.addSubview(RootVC.myLabel)
    // Add layout constraints here
    }

}
Attila Marosi
  • 144
  • 1
  • 8
0

As the error says you are not allowed to declare variables in extension.

You mention that you want to initialize the UI element in the extensions. of course you can do that. But, what you have in the extension is a declaration not only initialization.

Have the declaration in the controller and the initialization in an extension method.

hasan
  • 23,815
  • 10
  • 63
  • 101