【问题标题】:Assign textfield value to an array even after changing the value swift即使在快速更改值之后也将文本字段值分配给数组
【发布时间】:2021-12-09 22:35:19
【问题描述】:

我有一个文本字段,我想将文本字段值存储到一个数组中,以便我可以将此字符串传递给 API 请求。 使用 textfield 委托方法获取 textfield 值,如下所示:

var phoneNo = [String]()
 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            switch textField {
            
            case contact_PhoneNumberTextField:
                guard let text = textField.text else { return false }
                let newString = (text as NSString).replacingCharacters(in: range, with: string)
                textField.text = formatPhoneNumber(phoneString: newString)
                return false
            
            default:
                return true
            }
            
        }
    
      func textFieldDidEndEditing(_ textField: UITextField) {
    
            if textField == contact_PhoneNumberTextField{
                
                phoneNo.append(getOriginalPhoneNumber(phone: textField.text ?? ""))
            }
    }

问题在于将文本字段附加到 phoneNo 数组。文本字段值最初存储到一个数组中。假设如果我更改同一个文本字段的值,那么它将在数组中创建另一个值,而不是我想替换数组中的相同值,避免在数组中创建多个值。如何实现?

【问题讨论】:

  • 您需要跟踪您正在更改的对象,可能通过跟踪其在数组中的索引或原始值,以便您可以找到并用编辑后的值替换它
  • 你为什么要追加?只需替换整个字符串。
  • @JoakimDanielson 你能告诉我需要做什么吗?
  • 在阅读了@Rob 的评论后,我现在看到你没有一个数组而是一个字符串来存储你的值,所以我之前的评论不再相关了。鉴于此和下面的评论,我相信您需要重新考虑您的整个解决方案。也许您应该花时间创建一个自定义结构来保存文本字段的值

标签: arrays swift duplicates append textfield


【解决方案1】:

正如@Rob 提到的,phoneNo 是一个字符串,和数组一样,它在 Swift 中有 append,但这并不意味着你需要使用它。如果phoneNo 只能有一个值,例如“04111111111”,则只需将新值替换为旧值!

这样的:

    func textFieldDidEndEditing(_ textField: UITextField) {

        if textField == contact_PhoneNumberTextField{
            phoneNo = getOriginalPhoneNumber(phone: textField.text ?? "")
        }
   }

仅供参考:

【讨论】:

  • 我想将它存储在一个数组中,因为有很多文本字段及其值。如果第一个文本字段存储在数组中并且如果我再次更改第一个文本字段值,那么存储的值也应该是替换。
猜你喜欢
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多