我得到一个plist
对象,其中包含所有单词key=english
和value=malay
,然后分配给2个不同的数组,分别为english
和malay
。现在我想要一个textfield
,我想在其中搜索english
单词并在malay
中打印label
单词。
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
@IBOutlet weak var selectedLabel: UILabel!
@IBOutlet weak var searchText: UITextField!
@IBOutlet weak var wordTable: UITableView!
var english = [String]()
var malay = [String]()
var words: [String: String] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wordTable.dataSource = self
wordTable.delegate = self
searchText.delegate = self
if let path = Bundle.main.path(forResource: "words", ofType: "plist"){
if let plistData = FileManager.default.contents(atPath: path){
do {
let plistObject = try PropertyListSerialization.propertyList(from: plistData, options: PropertyListSerialization.ReadOptions(), format: nil)
words = (plistObject as? [String: String])!
english = [String] (words.keys)
malay = [String] (words.values)
} catch {
print("Error Serialize")
}
} else {
print("Error reading data")
}
} else {
print("Property list")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return english.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
cell = tableView.dequeueReusableCell(withIdentifier: "tabelCell")
if cell == nil {
cell = UITableViewCell(
style: UITableViewCellStyle.value2,
reuseIdentifier: "tableCell")
print("creating a table cell")
}
cell!.textLabel!.text = english[indexPath.row]
cell!.detailTextLabel?.text = malay[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedLabel.text = malay[indexPath.row]
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
@IBAction func searchBtn(_ sender: UIButton) {
let result = words.filter {$0.key == searchText.text}
if result.count > 0 {
print(result)
selectedLabel.text! = result.values //error
} else {
print("Not found")
}
}
}
我期望的输出是textfield(Bus)
,即english
个字,然后在label
中向我显示malay
个字(基本)
答案 0 :(得分:0)
为什么不搜索plist对象?我认为这很简单
@IBAction func searchBtn(_ sender: UIButton) {
guard let words = plistObject as? [String: String], let key = searchText.text else { return }
selectedLabel.text = words[key] ?? ""
}
这样的事情。
答案 1 :(得分:0)
搜索不需要使用两个不同的arrays
。 filter
和dictionary
都可以使用array
方法。因此,假设在字典示例下面:
let plist = ["apple": "red", "orange": "orange", "banana": "yellow", "grapes": "green", "pineapple": "light yellow"]
并且搜索键为"app"
,所以
let searchedText = "app"
let result = plist.filter {$0.key == searchedText}
if result.count > 0 {
print(result)
} else {
print("Not found")
}
输出:[“苹果”:“红色”]