Autocomplete for Xamarin iOS17 Jul 2016
Do you have a UITextField on which you want to add some autocomplete magic? Then you’re in luck, i’ve made an autocomplete UITextfield for Xamarin iOS.
The library is not an out of the box solution that looks perfectly on everything. It has some default behaviour which you can use to setup an autocomplete field really quick if that is what you want. But the nice thing about this library is that it is completely customizable.
- Add the package to your project.
- In the interface builder select the textfield that you want to have autocomplete functionality and bind it to the viewcontroller(In Xamarin studio, VS or Interface builder)
- Change the class to “MBAutoCompleteTextField”
- Call the setup method in the ViewDidAppear
Customize behaviour and appearance
MBAutocomplete functionality consists of three steps that it uses to bring you the results, these step are completely customizable:
- It has to fetch data from a source when a new character has been inserted
- The fetched data needs to be sorted using an algorithm(or it has already been sorted)
- The results of the sorted data needs to be displayed
1. Fetching data
All these steps are replaceable in MBAutoComplete by implementing the interfaces and settings the property of the MBAutoComplete UITextField. The simplest way to display data is to pass in a Collection of strings:
When you have a more advanced use case you can create a class and implement the IDataFetcher interface. Set that class as the datafetcher for your UITextField and you’re done. For example: if you want to fetch some strings from a webserver you could do something like this.
2. Sorting data
Sorting the strings is done by using an algorithm. On default there is no algorithm set. This is convenient for users who fetch data from a webserver that are already sorted. Nevertheless there are some use cases in which you still want to sort the data. You can do that by implementing the ISortingAlghorithm interface and setting the SortingAlgorithm property of the MBAutoCompleteTextField. For example:
3. Displaying the results
The results will be displayed in rows inside a TableView that positions itself underneath the textfield. If you want to customize you can can set your own AutoCompleteViewSource and use custom cells and style it in any way you wish. For example:
The source is hosted on github (https://github.com/MarcBruins/MBAutoComplete) and it’s also available as a nuget package (https://www.nuget.org/packages/MBAutoComplete/). Feel free to send pull requests!