iosuiviewuiviewcontrollerpropertiescustom-controls

Adding and changing a custom UIView programmatically (Swift)


I am trying to create a custom UIView that I can use in my other UIViewControllers.

The custom view:

import UIKit

class customView: UIView {

    override init(frame: CGRect) {

        super.init(frame:frame)

        let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 100))
        addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Then I want to add it in to a separate UIViewController:

let newView = customView(frame:CGRectMake(0, 0, 500, 400))
self.view.addSubview(newView)

This works to display the view, but what do I need to add to be able to change the properties (such as myLabel) from the UIViewController that is embedding the customView?

I'd like to be able to access and change the label from the viewController, allowing me to change text, alpha, font, or hide the label using dot notation:

newView.myLabel.text = "changed label!"

Trying to access the label now gives the error "Value of type 'customView' has no member 'myLabel'"

Thanks so much for any help!


Solution

  • This is because the property myLabel is not declared at the class level. Move the property declaration to class level and mark it public. Then you will be able to access it from outside.

    Something like

    import UIKit
    
    class customView: UIView {
    
        public myLabel: UILabel?    
        override init(frame: CGRect) {
    
            super.init(frame:frame)
    
            myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 100))
            addSubview(myLabel!)
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }