現在tableviewに複数のtextfieldがあり、全てのtextfieldが空の時は画面右上のbarbuttonitemをタップ不可にし、どれかに文字が1文字でも入るとbarbuttonitemをタップ可能にしたいのですが、以下のようにしてもうまくいきません。2文字目を入力した段階でbarbuttonitemがタップ可能になりますし、文字を全て消してもbarbuttonitemはタップ可能で、次に1文字入力するとbarbuttonitemがタップ不可能になるというように1アクション遅れます。
swift
1func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 2 let filledTextFieldCells = self.tableView.visibleCells.filter { 3 if let cell = $0 as? Checkable { 4 return cell.isFilledTextField() 5 } else { 6 return false 7 } 8 } 9 if filledTextFieldCells.count == 0 { 10 self.navigationItem.rightBarButtonItem?.isEnabled = false 11 } else { 12 self.navigationItem.rightBarButtonItem?.isEnabled = true 13 } 14 15 return true 16 } 17 18class NameEditTableViewCell: UITableViewCell, Checkable { 19 20 @IBOutlet weak var nameTextField: UITextField! 21 22 func isFilledTextField() -> Bool { 23 return !self.nameTextField.text!.isEmpty ? true : false 24 } 25 26} 27
どうすれば入力と同時にtextfieldが空なのかどうかを判別することができるでしょうか?
どなたかわかる方がいれば教えていただきたいです。よろしくお願いします。
///回答を受けての追記///
swift
1func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 2 let newText = (textField.text as! NSString).replacingCharacters(in: range, with: string) 3 4 let filledTextFieldCells = self.tableView.visibleCells.filter { 5 if let cell = $0 as? Checkable { 6 return cell.isFilledTextField(text: newText) 7 } else { 8 return false 9 } 10 } 11 if filledTextFieldCells.count == 0 { 12 self.navigationItem.rightBarButtonItem?.isEnabled = false 13 } else { 14 self.navigationItem.rightBarButtonItem?.isEnabled = true 15 } 16 17 return true 18 } 19 20extension Checkable { 21 func isFilledTextField(text: String) -> Bool { 22 return !text.isEmpty ? true : false 23 } 24}
///notificationを使ったやり方に変更///
swift
1func didChangeNotification(notification: Notification) { 2 var noEmptyTextField = true 3 4 if let textField = notification.object as? UITextField { 5 switch textField.tag { 6 case CellTag.name.rawValue: 7 if let text = textField.text, !text.isEmpty { 8 noEmptyTextField = true 9 } else { 10 noEmptyTextField = false 11 } 12 case CellTag.category.rawValue: 13 if let text = textField.text, !text.isEmpty { 14 noEmptyTextField = true 15 } else { 16 noEmptyTextField = false 17 } 18 case CellTag.price.rawValue: 19 if let text = textField.text, !text.isEmpty { 20 noEmptyTextField = true 21 } else { 22 noEmptyTextField = false 23 } 24 default: 25 break 26 } 27 } 28 29 if noEmptyTextField { 30 self.navigationItem.rightBarButtonItem?.isEnabled = true 31 } else { 32 self.navigationItem.rightBarButtonItem?.isEnabled = false 33 } 34 } 35
回答2件
あなたの回答
tips
プレビュー