0

I've been trying to make an app in Xcode 9 using Swift and I'm trying to refresh the label display when battery level changes.

But everytime I use "label.text = value" I get an error that says Instance member 'LineTwo' cannot be used on type 'ViewController'.

I'm not sure why I'm getting this error.

Here is my full code.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var LineTwo: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    UIDevice.current.isBatteryMonitoringEnabled = true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

let observer = NotificationCenter.default.addObserver(
    forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
    object: nil, queue: nil) {_ in

        let msgOne = String(Int(UIDevice.current.batteryLevel*100))+"% ,Battery changed!"
        print(msgOne)
        LineTwo.text = msgOne //error:Instance member 'LineTwo' cannot be used on type 'ViewController'
        }
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Mitchell
  • 3
  • 3
  • You're creating the observer outside of the `ViewController` class, so you need an object of `ViewController` to access this `LineTwo` object. Or simply move this code inside `ViewController` class – Mukesh May 02 '18 at 09:30
  • check this : https://stackoverflow.com/questions/34012063/instance-member-cannot-be-used-on-type-viewcontroller – Sagar Shirbhate May 02 '18 at 09:37
  • Move your code inside `viewDidLoad`. I would use `NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: .UIDeviceBatteryLevelDidChange, object: nil)` and then run your code inside `@objc func batteryLevelChanged(_ notification: Notification) { // }` – rbaldwin May 02 '18 at 09:44
  • simply initialize observer inside viewDidLoad method, don't forget to user self.LineTwo inside the closure – Moayad Al kouz May 02 '18 at 09:45

0 Answers0