2016-12-30 6 views
3

Я записал свой экран и here is the link to it. вдаваясь в подробностиSwift UITextField текст удаляется с действием кнопки в TableViewCell

  1. У меня есть раздел Tableview, в котором есть tableviewcell (PhoneCell) с двумя TextFields (один входной сигнал pickerview и другие текстовое поле), и кнопка Добавить.
  2. Когда кнопка «Добавить» нажата, я добавляю пустой телефон в массив телефонов (повторно используя тот же PhoneCell) и вызывая метод tableView.reloadData().

Проблема :(
Всякий раз, когда я нажимаю на кнопку Добавить, текст TextFields, что я вхожу очищается. Я хотел бы сохранить его и в конечном счете, должны быть в состоянии сохранить данные (количество телефонов пользователь вошел), когда я нажимаю Save_Button

добавить код кнопки телефона действие:

func addUserPhone(userData: MyUserData) { 
     self.user = userData 

     var emptyPhoneDict:[String:String] = ["country":"", "number":""] 

     if (user.phones?.count < 4) { 
      var emptyPhone : MyUserPhoneNumber = MyUserPhoneNumber(dictionary: emptyPhoneDict)! 
      emptyPhone.country = "" 
      emptyPhone.number = "" 
      user.phones?.append(emptyPhone) 
     } 
    } 

В моем PhoneCell.swift класса, У меня есть ниже метод, который заботится о данных и indexPath значения

override func configure(withUser user: MyUserData, language: String, indexPath: NSIndexPath) { 
     super.configure(withUser: user, language: language, indexPath: indexPath) 

     configureCountryCodePicker() 
     fetchCountryTeleCodeList() 

     userInfo = user 

     self.countryCode.borderStyle = .RoundedRect 
     self.teleNumber.borderStyle = .RoundedRect 

     if user.phones?.count == 0 { 
      self.countryCode.text = "" 
      self.teleNumber.text = "" 
     } 

     else { 
      if let userPhoneInfo = user.phones { 

       self.countryCode.text = userPhoneInfo[indexPath.row].country 
       self.teleNumber.text = userPhoneInfo[indexPath.row].number 

      } 
     } 
    } 

EDIT (ДОБАВЛЕНО cellForRowAtIndexPath)

public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     guard let section = Section(rawValue: indexPath.section) else { 
      print("❌ Invalid section index.") 
      return UITableViewCell() 
     } 

     let expanded = expandedCellPaths.contains(indexPath) 

     var cell: ProfileCell? 

     switch section {  

     case .ContactPhones: 
      if contactCellExpanded == true { 
       cell = tableView.dequeueReusableCellWithIdentifier("PhoneCell") as? PhoneCell 
       (cell as? PhoneCell)?.dataSource = self 

       if user.phones?.count == 4 { 
        (cell as! PhoneCell).addPhoneButton.hidden = true 
       } 
       else { 
        (cell as! PhoneCell).addPhoneButton.hidden = false 
       } 

      } 
     case .ContactEmail: 
      if contactCellExpanded == true { 
       cell = tableView.dequeueReusableCellWithIdentifier("EmailCell") as? EmailCell 
      } 

     default: 
      break 
     } 

     cell?.configure(withUser: user, language: languageCode, indexPath: indexPath) 
     cell?.delegate = self 

     return cell ?? UITableViewCell() 

    } 

EDIT 2 (добавлен addPhoneButtonAction)

@IBAction func addPhoneButtonAction(sender: AnyObject) { 
     self.dataSource?.addUserPhone(userInfo!) 
    } 

Где dataSource переменная протокола PhoneCellDataSource типа

protocol PhoneCellDataSource : class { 

    func fetchCountryTeleCodeList(completion:((XtraResult<NSArray, XtraError>) -> Void)) 
    func addUserPhone(userData: MyUserData) 

} 

я могу разделить больше входов/код по мере необходимости. Пожалуйста помоги. Заранее спасибо!

+0

Nicely создан GIF для решения lohit .. . :) Не могли бы вы проглотить свой код cellForRowAtIndexPath? –

+0

@DheerajD: thank you :-) Я добавил cellForRowAtIndexPath в свой вопрос –

+0

@LohithKorupolu Вы можете показать действие кнопки 'addPhoneButton'? –

ответ

0

Я собираюсь ответить на мой собственный вопрос ;-)

TextFeilds являются только ящики, которые приспосабливают некоторые данные (текст). И так как я повторно использовал Phonecell каждый раз, когда добавляю новую строку, текст, который я вводил, стирается. Это связано с тем, что он не «сохранен/сохранен» в объекте пользователя.

Так что в моем методе addPhoneButtonAction, я добавил это -

@IBAction func addPhoneButtonAction(sender: AnyObject) { 
     userInfo?.phones![myIndexPath!.row].country = countryCode.text! 
     userInfo?.phones![myIndexPath!.row].number = teleNumber.text! 

     self.dataSource?.addUserPhone(userInfo!) 
    } 

Где myIndexPath является indexPath из строки :-)

Рабочая sample is here

Смежные вопросы