我正在使用api。我发布一些数据并将响应存储在tableview中。我把搜索栏从表视图中搜索数据。我想在搜索栏中写3个字之后,api会调用,并且数据会在tableview中显示。我正在使用uitextfield搜索栏。
var array = [String]()
var tabledata = [String]()
var tableFilterData = [String]()
var isSearch :Bool!
let cellReuseIdentifier = "cell"
@IBOutlet weak var searchTextfield: UITextField!
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBAction func textfieldchanged(_ sender: Any) {
tableview.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
isSearch = false
self.apicalling()
searchTextfield.addTarget(self, action: #selector(textFieldActive), for: UIControlEvents.touchDown)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
var searchText = textField.text! + string
if string == "" {
searchText = (searchText as String).substring(to: searchText.index(before: searchText.endIndex))
}
if searchText == "" {
isSearch = false
tableview.reloadData()
}
else{
getSearchArrayContains(searchText)
}
return true
}
func getSearchArrayContains(_ text : String) {
var predicate : NSPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", text)
tableFilterData = (tabledata as NSArray).filtered(using: predicate) as! [String]
isSearch = true
tableview.reloadData()
}
override func viewDidLayoutSubviews()
{
heightConstraint.constant = tableview.contentSize.height
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
guard let touch:UITouch = touches.first else
{
return;
}
if touch.view != tableview
{
searchTextfield.endEditing(true)
tableview.isHidden = true
}
}
@objc func textFieldActive() {
tableview.isHidden = !tableview.isHidden
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
我的tableview部分是
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearch! {
return tableFilterData.count
}
else{
return tabledata.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell!
// Set text from the data model
if isSearch! {
cell.textLabel?.text = tableFilterData[indexPath.row]
cell.textLabel?.font = searchTextfield.font
}
else{
cell.textLabel?.text = tabledata[indexPath.row]
cell.textLabel?.font = searchTextfield.font
}
return cell
}
在我的api中,调用我的参数是
let param = ["var_name": "sha","API":"user_search","auth_token":authToken!]
但是我想将searchdata传递给“ var_name”。 我的搜索栏工作正常,但是我想在该API调用后在搜索栏中写3个字并将三个数据作为参数传递给api中的“ var_name”中。