Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 602
RanLearns Avatar asked Dec 04 '15 03:12

RanLearns


People also ask

How create custom UIView in programmatically in Swift?

Open Xcode ▸ File ▸ New ▸ File ▸ Cocoa Touch class ▸ Add your class name ▸ Select UIView or subclass of UIView under Subclass of ▸ Select language ▸ Next ▸ Select target ▸ Create the source file under your project directory. Programatically create subviews, layout and design your custom view as per requirement.

How do I load a view programmatically in Swift?

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super. viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let myNewView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200)) // Change UIView background colour myNewView.

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.


1 Answers

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)
    }
}
like image 177
Shamas S Avatar answered Sep 22 '22 10:09

Shamas S