Lex.driver Lex.driver - 6 months ago 121
Swift Question

Value of type 'UIView' has no member 'tableView'

I have the error:


Value of type 'UIView' has no member 'tableView'


occur when I attempt to change the background of the tableView in the
viewWillAppear
method.

I expected the table view would already be initialised from the
viewDidLoad
method.

Where should I be trying to change the colours for the tableview? Should I also be changing the other background colours in the same place?

class settingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

override func viewDidLoad() {
super.viewDidLoad()

// Table view setup
let tableView = UITableView(frame: view.bounds, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(settingsCell.self, forCellReuseIdentifier: NSStringFromClass(settingsCell))
view.addSubview(tableView)

}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)

if nightMode == true {
view.backgroundColor = UIColor.blackColor()
view.tableView.backgroundColor = UIColor.blackColor() // Error here..
}
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(settingsCell), forIndexPath: indexPath) as! settingsCell

// Fetch setting
let cellSetting = settings[indexPath.row]

// Configure Cell
cell.textLabel?.text = cellSetting.name

return cell
}
}

Answer

You can make it an instance variable of UITableView like

 class settingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 var tableView:UITableView!
 override func viewDidLoad() {
      super.viewDidLoad()

      // Table view setup
      tableView = UITableView(frame: view.bounds, style: .Plain)
      tableView.delegate = self
      tableView.dataSource = self
      tableView.registerClass(settingsCell.self, forCellReuseIdentifier: NSStringFromClass(settingsCell))
      view.addSubview(tableView)
}

override func viewWillAppear(animated: Bool) {
     super.viewWillAppear(true)

     if nightMode == true {
         view.backgroundColor = UIColor.blackColor()
         tableView.backgroundColor = UIColor.blackColor()
     }
}