TungVuDuc
TungVuDuc

Reputation: 19

Error : Instance member cannot be used on type 'ViewController'

I created a subclass of UIView below :

import UIKit

class MenuBar : UIView {

    override init(frame : CGRect ){
        super.init(frame: frame)
        setupViews()
       }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
    func setupViews(){

      }
}

then, I want to add it to my ViewController :

let menuBarView : MenuBar = {

        let mbv = MenuBar(
        mbv.translatesAutoresizingMaskIntoConstraints = false
        mbv.backgroundColor = UIColor.green
        return mbv
    }()

But it return an error : instance member 'MenuBar' cannot be used on type 'ViewController'

Upvotes: 0

Views: 3655

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20369

Not really sure, but your code should not even compile as your lazy variable instantiation of menubar says

let mbv = MenuBar(

Which it should be

let mbv = MenuBar()

Final working code would be

let menuBarView : MenuBar = {

        let mbv = MenuBar()
        mbv.translatesAutoresizingMaskIntoConstraints = false
        mbv.backgroundColor = UIColor.green
        return mbv
    }()

Tested it, it works absolutely fine.

EDIT:

This is how am using it and it is working fine!

//other variable declaration
    let menuBarView : MenuBar = {
        let mbv = MenuBar()
        mbv.translatesAutoresizingMaskIntoConstraints = false
        mbv.backgroundColor = UIColor.green
        return mbv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(menuBarView)

        // Do any additional setup after loading the view, typically from a nib.
    }

Upvotes: 1

Related Questions