given an array create an auto complete textfield in swift

To create an auto-complete text field in Swift, we can use a UITableView to display the suggestions based on the user’s input.

First, we need to create a UITextField and set ourselves as the delegate. We also need to create a UITableView and add it below the text field, making sure to set the UITableViewDataSource and UITableViewDelegate to self.

Let’s assume we have an array of words that we want to suggest, called suggestions. We can use this array to filter the suggestions based on what the user types in the text field. We can implement the textFieldDidChange method of the UITextFieldDelegate to handle this filtering.

main.swift
class AutoCompleteTextField: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    var suggestions: [String] = ["Apple", "Banana", "Cherry", "Dates", "Eggfruit", "Fig", "Grape", "Honeydew", "Ice apple", "Jackfruit", "Kiwi", "Lemon", "Mango", "Nectarine", "Orange", "Papaya", "Quince", "Raspberry", "Strawberry", "Tomato", "Ugli fruit", "Vanilla bean", "Watermelon", "Xigua", "Yellow passionfruit", "Zucchini"]
    
    var filteredSuggestions: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.isHidden = true
        
        tableView.dataSource = self
        tableView.delegate = self
        
        textField.delegate = self
    }
}

extension AutoCompleteTextField: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        let searchText = textField.text ?? ""
        filteredSuggestions = suggestions.filter({ $0.lowercased().contains(searchText.lowercased()) })
        tableView.reloadData()
        tableView.isHidden = filteredSuggestions.isEmpty
    }
}

extension AutoCompleteTextField: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredSuggestions.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = filteredSuggestions[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        textField.text = filteredSuggestions[indexPath.row]
        tableView.isHidden = true
    }
}
1828 chars
47 lines

In this code, we have defined suggestions and filteredSuggestions. suggestions contains all the words that we want to suggest, while filteredSuggestions contain the words that match the user's input.

In viewDidLoad, we hide the table view and set the UITableViewDataSource and UITableViewDelegate to self, as well as set the text field's delegate to self.

In textFieldDidChangeSelection, we filter the suggestions based on the user input and update filteredSuggestions accordingly. We also show or hide the table view based on whether the suggestions are empty or not.

In numberOfRowsInSection, we return the count of the filtered suggestions. In cellForRowAt, we display the filtered suggestions in each cell.

Finally, in didSelectRowAt, we set the text field's text to the selected suggestion and hide the table view.

Note that this is a basic implementation, and you may need to modify it depending on your requirements. For example, you may want to limit the number of suggestions shown in the table view, or customize the appearance of the table view cells.

gistlibby LogSnag