Thursday, 27 April 2017

Integrate search functionality in iOS app using Swift3


Integrate search functionality in iOS app using Swift3

Introduction to how to integrate search functionality using Swift3

This tutorial is focused on how to integrate search functionality within our app using swift language. Sometimes we got requirement where a large list displayed to user and at the top there is search bar from where user can perform search to sort out the listing as per text input. We will implement same search functionality using swift language in this tutorial. You can also use UISearchBar, but here we are using UITextField which acts as our search-bar, so this tutorial is focused on search using UITextfield in swift language. If you are looking for objective C version, check below link showing how to implement search using UITextField in iOS

 http://www.iostutorialjunction.com/2015/06/search-using-uitextfield-tutorial.html

Designing our User-Interface

Create a new single view application and name it "Search_Using_textField_Swift3". Open up main.storyboard and drag an UITableView and UITextField to it as shown in the image given below.

Adding UITableView and UITextField to our ViewControllers while developing  tutorial Search Using UITextField Swift3

Open ViewController.swift and create IBOutlet's to UITableView and UITextField so that we can connect them to our main.storyboard. Also we will create two arrays
1)  countriesArray : Array holding our original data i.e. in this case we are showing countries list
2) searchedArray :  Array holding searched results only.

The trick here is to assign all objects of originalArray to searchedArray and populate UITableView.
After populating UITableView we will add target to out UITextField for events editingchanged. Connect your Outlets before moving forward in the tutorial.

Below is the code for the whole things we discussed so far.




At this moment, you can see UITableView is showing countries names. So it's time to add search functionality and implement searchRecordsAsPerText function. Below is the code that implements the same.




Now run your code and you will see UITableView is changing data as per searched text.

Where to go from here

In this tutorial you learned, how to integrate search functionality in your app using Swift3 language. Stay tuned for more tutorials. You can download full source code from here Download source code for Search Using UITextField in Swift3

No comments:
Write comments