Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

swift - How to access Search Bar on tap callback

Im building an app and I have a search bar with table view. But I don't how when users tap the search, go to the data at different View Controller Someone can help me pls ? My code almost like that

@IBOutlet weak var textSearchBar: UITextField!
@IBOutlet weak var tableSearchResult: UITableView!

var fruitsArray:[String] = Array()
var searchedArray:[String] = Array()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
    fruitsArray.append("Apple")
    fruitsArray.append("Orange")
    fruitsArray.append("Litch")
    fruitsArray.append("Pineapple")
    
    for str in fruitsArray {
        searchedArray.append(str)
    }
    tableSearchResult.dataSource = self
    textSearchBar.delegate = self
}

// Mark:- UITableViewDataSource

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return searchedArray.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    
    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        
    }
    
    cell?.textLabel?.text = searchedArray [indexPath.row]
    return cell!
}

    // MARK: - UITextFieldDelegate

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    textSearchBar.resignFirstResponder()
    textSearchBar.text = ""
    self.searchedArray.removeAll()
    for str in fruitsArray {
        searchedArray.append(str)
    }
    tableSearchResult.reloadData()
    return true
}

Thank you Very Much

question from:https://stackoverflow.com/questions/66054989/how-to-access-search-bar-on-tap-callback

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

extension ViewController: UISearchBarDelegate {
    func searchBar(
        _ searchBar: UISearchBar,
        textDidChange searchText: String
    ) {
        // Here instructions for when searchBarText change 
    }
    
    func searchBarCancelButtonClicked(
        _ searchBar: UISearchBar
    ) {
        self.searchBar.endEditing(true)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...