How to change the text field value using Javascript

Search bar with history - Swift UI, SQLite

SQLite is used to store the data locally in the app in the SQL structure. It's a relational local database. You can use this database to store data in the app using Swift and Swift UI.

We're going to create a simple iOS app in the Swift UI to find animals from an array and store the user's searched strings in the SQLite database.

We're going to be using a library called SQLite from Stephen Celis. To install this library, Cocoapods must be installed on your system.

You can install Cocoapods in your system by simply running the following command in your terminal:

sudo gem install cocoapods

First, you need to open a command prompt (Terminal) in the root directory of your XCode project and run the following command:

pod init

Now you will see a new file created in the root directory of your project named Podfile. Open this file in your text editor and add the line to install the library. The following will be the content of your pod file:

# Uncomment the next line to define a global platform for your project # platform: ios, '9.0' target 'SQLite_Database' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for SQLite_Database pod 'SQLite.swift', '~> 0.12.0' end

After that, run the following command in your terminal to install this library:

pod update

After the installation, close your XCode and open it again. This time, however, double-click the file with the extension ".xcworkspace". This file is only created after the pod is installed / updated.

First, let's create a search bar with a TextField. When the user then clicks "Send", we send the value we are looking for in the next view.

In the second view we get the value from the text field of the first view and look for this value in an array. Then view all the records that match the string you are looking for and view them in List View.

Create status variables in your content view:

// variable to goto search view @State var gotoSearchPage: Bool = false // value that is searched from the text field @State var searchedText: String = ""

The following are the contents of the contents of your content view:

// live tracking of input field value let binding = Binding (get: {self.searchedText}, set: {(value) in self.searchedText = value}) // navigation view to goto search view return NavigationView {VStack (alignment: .leading, spacing: 10) {// navigation link to goto search view NavigationLink (destination: SearchView (searchedText: self. $ searchedText), isActive: self. $ gotoSearchPage) {EmptyView ()} // search field TextField ("Search ...", text: binding, onCommit: {// goto search view when search icon is clicked self.gotoSearchPage = true}) .padding (7) .padding (.horizontal, 5) .background (Color ( .systemGray6)) .cornerRadius (8) .disableAutocorrection (true) .keyboardType (.webSearch)} .padding (20) .navigationBarTitle ("Search - SQLite")}

This will create a text box for you to type your query into. If you click on the “search symbol” you will be taken to the search view that we will create in the next step.

Now we need to create a search view in which we will do the search and display the filtered records in a list view.

Create a modal class for Animal:

// // Animal.swift // Search bar with history // // Created by Adnan Afzal on 02/12/2020. // Copyright © 2020 Adnan Afzal. All rights reserved. // import Foundation class Animal: Identifiable {var id: Int64 = 0 var name: String = "" init () {//} init (name: String) {self.name = name}}

Create a new file named SearchView.swift and paste the following code:

// // SearchView.swift // Search bar with history // // Created by Adnan Afzal on 02/12/2020. // Copyright © 2020 Adnan Afzal. All rights reserved. // import SwiftUI struct SearchView: View {// get searched value from the previous view @Binding var searchedText: String // a list of all items (change this variable as per your need) @State var animals: [Animal] = [ ] // list of items that matched the searched text @State var searchedArray: [Animal] = [] var body: some View {VStack {// show searched text Text ("(searchedText)"). bold () // show items that matched the searched text in list view List (self.searchedArray) {(item) in Button (action: {//}, label: {Text (item.name)})}} .onAppear (perform: {// make the items empty when the page loads self.animals.removeAll () // add the data that needs to be searched (you can put your ow n array items here) self.animals.append (Animal (name: "Lion")) self.animals.append (Animal (name: "Tiger")) self.animals.append (Animal (name: "Rhino")) self.animals.append (Animal (name: "Elephant")) self.animals.append (Animal (name: "Cheetah")) self.animals.append (Animal (name: "Polar bear")) self.animals. append (Animal (name: "Leopard")) self.animals.append (Animal (name: "Wolf")) // empty the searched array self.searchedArray.removeAll () // find all the elements that matched the searched string for animal in self.animals {if (animal.name.lowercased (). contains (self.searchedText.lowercased ())) {self.searchedArray.append (animal)}}})}} struct SearchView_Previews: PreviewProvider {// when using @Binding, use this in preview provider @State static var searchedText: String = "" static var previews: some View {SearchView (searchedText: $ searchedText)}}

Comments have been added to each line to explain each line individually. Now you can do the search and see the animals that contain the name field that matches the text field value entered in the first view.

Now we need to see the search history in the content view. To do this, we first need to store each searched string in the SQLite database.

Create a separate class called "DB_Manager”, Which contains all functions for the SQLite database.

// // DB_Manager.swift // Search bar with history // // Created by Adnan Afzal on 02/12/2020. // Copyright © 2020 Adnan Afzal. All rights reserved. // import Foundation // import library import SQLite class DB_Manager {// sqlite instance private var db: Connection! // table instance private var animals: Table! // columns instances of table private var id: Expression ! private var name: Expression ! // constructor of this class init () {// exception handling do {// path of document directory let path: String = NSSearchPathForDirectoriesInDomains (.documentDirectory, .userDomainMask, true) .first ?? "" // creating database connection db = try Connection ("(path) /my_animals.sqlite3") // creating table object animals = Table ("animals") // create instances of each column id = Expression (" id ") name = Expression (" name ") // check if the animal's table is already created if (! UserDefaults.standard.bool (forKey:" is_db_created ")) {// if not, then create the table try db.run (animals.create {t.column (id, primaryKey: true) t.column (name)}) // set the value to true, so it will not attempt to create the table again UserDefaults.standard.set (true, forKey: "is_db_created")}} catch {// show error message if any print (error.localizedD escription)}} // check if record already exists in SQLite public func isExists (searchedText: String) -> Bool {var isExists: Bool = false // exception handling do {// get animal using ID let animal: AnySequence = try db.prepare (animals.filter (name.lowercaseString == searchedText.lowercased ())) // get row animal.forEach ({(rowValue) in isExists = true})} catch {print (error.localizedDescription)} return isExists} // add a new row in SQLite public func addAnimal (nameValue: String) {do {try db.run (animals.insert (name <- nameValue))} catch {print (error.localizedDescription)}}}

Comments have been added to each line for clarification. Well, in your search view within the onAppear () Function, check whether the string you are looking for already exists in the SQLite database. If NOT, paste the text you are looking for into the SQLite database.

// add the searched text in SQLite database if NOT exists let isExists: Bool = DB_Manager (). isExists (searchedText: self.searchedText) if (! isExists) {DB_Manager (). addAnimal (nameValue: self.searchedText)}

Now we need to show the search history in the main content view when the user clicks the search bar text box. So create two state wrapper properties in your content view:

// variable to show search history view @State var showSearchHistoryView: Bool = false // array of history array @State var history: [Animal] = []

And in the body we have to follow the live text change of the input field. We have already created a binding variable in the main part of the content view. Change the binding variable in the main part of the content view as follows:

// live tracking of input field value let binding = Binding (get: {self.searchedText}, set: {(value) in self.searchedText = value // show history if the text field is not empty self.showSearchHistoryView =! self.searchedText.isEmpty})

Well if that showSearchHistoryView Variable is true, we need to display a list of all the strings we searched before So create a list view under one if Condition below the search bar text field:

// show history view only when a variable is true if (self.showSearchHistoryView) {// create list view to show all history items List (self.history) {(model) in // show history text HStack {Image (systemName: "arrow.counterclockwise") Button (action: {self.searchedText = model.name self.gotoSearchPage = true}, label: {Text (model.name)})}}}

An icon for the counter clock appears, indicating that it is historical data. This button shows the previously searched character string and switches to the search view when clicked.

Now we need to load the data into ours history Array. So add a onAppear () Event to your VStack and get the data from the SQLite database and save it in the history array.

// load data in history models array .onAppear (perform: {self.history = DB_Manager (). getAnimals ()})

Now we need to create a function called getAnimals () in our DB_Manager Class that gets the records from the SQLite database.

// return array of animal models public func getAnimals () -> [Animal] {// create empty array var animalModels: [Animal] = [] // get all animals in descending order animals = animals.order (id.desc) // exception handling do {// loop through all animals for animal in try db.prepare (animals) {// create new model in each loop iteration let animalModel: Animal = Animal () // set values ​​in model from database animalModel. id = animal [id] animalModel.name = animal [name] // append in new array animalModels.append (animalModel)}} catch {print (error.localizedDescription)} // return array return animalModels}

Comments have been added to each line for clarification. Now, if you run the code, you can see all of the strings you were looking for in a list view. Clicking on it will take you to the search view screen.

Now we need a function to delete the string from the search history. First, create a button in your history list after the counter clock icon and the button in your content view:

... counter-clock icon and button // show delete button Spacer () Button (action: {// delete history item from SQLite DB_Manager (). deleteAnimal (idValue: model.id) // refresh the list view self.history = DB_Manager (). GetAnimals ()}, label: {Text ("Delete") .foregroundColor (Color.red)}) // by default, buttons are full width. // to prevent this, use the following buttonStyle (PlainButtonStyle ())

Now we need to create a function called deleteAnimal () in our DB_Manager Class that deletes the row from the SQLite database.

// function to delete animal from search history public func deleteAnimal (idValue: Int64) {do {// get animal using ID let animal: Table = animals.filter (id == idValue) // run the delete query try db.run (animal.delete ())} catch {print (error.localizedDescription)}}

Now run the code and you will see a delete button at the end of each line of history. When you click, the row is removed from the SQLite database and also from the list view.

Generate download link



[ad_2]