Я записал свой экран и here is the link to it. вдаваясь в подробностиSwift UITextField текст удаляется с действием кнопки в TableViewCell
- У меня есть раздел Tableview, в котором есть tableviewcell (PhoneCell) с двумя TextFields (один входной сигнал pickerview и другие текстовое поле), и кнопка Добавить.
- Когда кнопка «Добавить» нажата, я добавляю пустой телефон в массив телефонов (повторно используя тот же 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)
}
я могу разделить больше входов/код по мере необходимости. Пожалуйста помоги. Заранее спасибо!
Nicely создан GIF для решения lohit .. . :) Не могли бы вы проглотить свой код cellForRowAtIndexPath? –
@DheerajD: thank you :-) Я добавил cellForRowAtIndexPath в свой вопрос –
@LohithKorupolu Вы можете показать действие кнопки 'addPhoneButton'? –