【问题标题】:Instance method 'contains' requires that 'UITextField' conform to 'StringProtocol'实例方法“包含”要求“UITextField”符合“StringProtocol”
【发布时间】:2020-07-08 16:40:41
【问题描述】:

我有一个 tableview,它显示一个具有 Name 和 Category 属性的 sourceArray。我想根据来自 UIAlertController 的用户输入过滤 sourceArray 的 Category 属性,但收到错误“Instance method 'contains' requires that 'UITextField' conform to 'StringProtocol'”。非常感谢任何帮助。

var sourceArray = [(Name: String, Category: String, Picture1: UIImage, Picture2: UIImage, Picture3: UIImage, Description: String)]()

@IBAction func filterButton(_ sender: UIBarButtonItem) {
    var textField = UITextField()
    let alert = UIAlertController(title: "Category", message: nil, preferredStyle: .alert)
    let action = UIAlertAction(title: "Filter", style: .default) { (action) in
        print(textField)
        let filtered = sourceArray.filter({$0.Category.contains(textField)})
        self.filteredArray = filteredArray.isEmpty ? sourceArray : filtered
        self.tableview.reloadData()

    }
    alert.addTextField { (alertTextField) in
        alertTextField.placeholder = "Biceps, Chest, Shoulders, etc."
        textField = alertTextField
    }
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
    
}

【问题讨论】:

  • 什么是sourceArray
  • sourceArray 是我用来填充 tableView 的数组。它包含练习名称及其类别。
  • 你的代码没有意义。您创建一个新的、不与任何东西连接的 UITextField,然后尝试查看您的 sourceArray 是否包含该文本字段对象?
  • 代码不是创建了 textField 并创建了一个 UIAlertAction 来过滤 sourceArray 中的 textField 吗?这就是我理解的写法。
  • 我的逻辑很可能在这里行不通。我正在尝试根据 textField 中输入的内容过滤 sourceArray。有没有更好的方法来做到这一点?

标签: arrays swift uialertcontroller


【解决方案1】:

我遇到的这个问题是 textField 未被识别为字符串。所以我添加了一个常量文本作为字符串,并像这样将 textField.text 分配给它。

@IBAction func filterButton(_ sender: UIBarButtonItem) {
    var textField = UITextField()
    let alert = UIAlertController(title: "Category", message: nil, preferredStyle: .alert)
    let action = UIAlertAction(title: "Filter", style: .default) { (action) in
        
        let text: String = textField.text!
        let filtered = self.sourceArray.filter({$0.Category.contains(text)})
        self.filteredArray = self.filteredArray.isEmpty ? self.sourceArray : filtered
        self.tableview.reloadData()

    }
    alert.addTextField { (alertTextField) in
        alertTextField.placeholder = "Biceps, Chest, Shoulders, etc."
        textField = alertTextField
    }
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 2021-11-24
    • 2020-05-20
    • 1970-01-01
    • 2021-02-10
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多