![](/img/trans.png)
[英]Swift Array Sort by Property Error : Instance method 'localizedCaseInsensitiveCompare' requires that 'String?' conform to 'StringProtocol'
[英]Instance method 'contains' requires that 'UITextField' conform to 'StringProtocol'
我有一個表格視圖,它顯示一個具有名稱和類別屬性的 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)
}
我遇到的這個問題是 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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.