1

I have a project where people can assign a word when creating a collection view item and can use that term they assigned to the collection view item to search for it in another view, such as: someone creates item and names it 'milk' and then uses the work groceries so they can search for it later.

I am using CoreData and am saving that word upon the collection view item creation with an attribute, this it how my code looks for assigning the text fields filled in where the collection view cell is created:

@IBAction func doneTran(_ sender: UIButton) {

    if textFieldT.text != "" {


        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let task = Task(context: context)

        task.name = textFieldT.text!

        task.desc = descBox.text!

        task.hashtag = hashtagField.text!

        task.pid = pidStore

        (UIApplication.shared.delegate as! AppDelegate).saveContext()

        // Saves info to CoreData
    }

The hashtag is the one that stores the term to search with. I then have a new view controller where the item can be searched for using the the hashtag string. It uses a textField and a UIButton to reloadView and display items according to if their hashtag attribute matches the textField text. This is how I implemented it:

@IBOutlet weak var resultsColl: UICollectionView!

@IBOutlet weak var textFieldFHash: UITextField!

var taskTwo : [Task] = []

var activeCell : HashCollectionViewCell!

var testHashAt = String()

override func viewDidLoad() {
    super.viewDidLoad()

    self.resultsColl.delegate = self
    self.resultsColl.dataSource = self

    testHashAt = textFieldFHash.text!
}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    getData()
    resultsColl.reloadData()

    testHashAt = textFieldFHash.text!
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return taskTwo.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let taskTHash = taskTwo[indexPath.row]

    let cellHash = collectionView.dequeueReusableCell(withReuseIdentifier: "nCell", for: indexPath) as! HashCollectionViewCell

    if testHashAt == taskTHash.hashtag {
        cellHash.labelFHash?.text = taskTHash.name
    }
    else {
        print("blank cell?")
    }

    if cellHash.labelFHash.text == "" {
        print("cell is nil")
    }

    cellHash.layer.cornerRadius = 25

    return cellHash
}

@IBAction func searchHashBtn(_ sender: UIButton) {
    getData()
    resultsColl.reloadData()
}

func getData() {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do {
        let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
        fetchRequest.predicate = NSPredicate.init(format: "hashtag = %@", testHashAt);
        taskTwo = try context.fetch(fetchRequest)
    }

    catch {
        print("Get Data failed")
    }

    // Fetches data.
}

That is all the code in the view controller for searching but when I search for the term nothing comes up. I am not sure if this is a problem with the search button not actually reloading the view to show the cells or if the search function in general doesn't work. Does anyone know how to get the correct items to display according to their hashtag attribute?

Richard
  • 57
  • 4
  • 10
  • Possible duplicate of [How to make UITextField behave like a UISearchBar in Swift?](http://stackoverflow.com/questions/26446376/how-to-make-uitextfield-behave-like-a-uisearchbar-in-swift) – Darshit Shah Apr 11 '17 at 09:56

2 Answers2

4

Try with this below code :

import UIKit

class TDSearchVC: UIViewController ,   UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{


@IBOutlet var textSearch: UITextField!
@IBOutlet var tblSearchResult: UITableView!

var arrData : [String] = []
var arrFilterData : [String] = []
var isSearch : Bool!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    isSearch = false

    arrData = ["Apple", "Banana", "Chikoo", "Brew", "Cherry", "Mango", "Lotus", "Peacock", "Temple", "Pine Apple","Glass", "Rose", "Church", "Computer", "Carrot"]

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK:- textfield

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{

    var searchText  = textField.text! + string

    if string  == "" {
        searchText = (searchText as String).substring(to: searchText.index(before: searchText.endIndex))
    }

    if searchText == "" {
        isSearch = false
        tblSearchResult.reloadData()
    }
    else{
        getSearchArrayContains(searchText)
    }

    return true
}

// Predicate to filter data
func getSearchArrayContains(_ text : String) {
    var predicate : NSPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", text)
    arrFilterData = (arrData as NSArray).filtered(using: predicate) as! [String]
    isSearch = true
    tblSearchResult.reloadData()
}

// MARK:- TableView Delegates
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    if isSearch! {
        return arrFilterData.count
    }
    else{

        return arrData.count
    }
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    var cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell

    if isSearch! {
        cell.textLabel?.text = arrFilterData[indexPath.row]
    }
    else{

        cell.textLabel?.text = arrData[indexPath.row]
    }
    return cell
}
}
dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
-1

If you want to use TextField to search any word in tableView. You can use

func textFieldDidChangeSelection(_ textField: UITextField)

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
sametytmz
  • 9
  • 2