Home > Net >  accessing and setting label text userDefaults
accessing and setting label text userDefaults

Time:10-11

I've two userdefault values username and password, I want to set label which is inside tableView cell text those userdefaults, but my code only sets username not password

any solution?

class UDM {
    static let shared = UDM()
    let defaults = UserDefaults(suiteName: "saved.data")
}
    @IBAction func registerButton(_ sender: Any) {
        UDM.shared.defaults?.setValue(usernameRegister.text, forKey: "username")
        UDM.shared.defaults?.setValue(passwordRegister.text, forKey: "password")
        }  //  userdefaults are set succesfully
// table view controller
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? TableViewCell
        cell?.setup(with: UDM.shared,with: UDM.shared)
        return cell!
    }
///table view cell
    func setup(with username:UDM,with password:UDM){
        label.text = UDM.shared.defaults?.value(forKey: "password") as? String
        label.text = UDM.shared.defaults?.value(forKey: "username") as? String
    }

CodePudding user response:

I think you are assigning the same label different values.

If your read your code it first assign your label with password then it assign the same label with username. You have to make a label1 or label2.

func setup(with username:UDM,with password:UDM){
        label1.text = UDM.shared.defaults?.value(forKey: "password") as? String
        label2.text = UDM.shared.defaults?.value(forKey: "username") as? String
    }
  • Related