SearchBar shows right result, leads to wrong ViewController

0

I am putting together an app that shows the managers on Page1 and their respective employees on Page2. I decided to mount it on a plist and load it into a TableView, see:

Toloadtheplistcorrectly,IinsertedthefollowingcodeintoAppDelegate:

classAppDelegate:UIResponder,UIApplicationDelegate{varwindow:UIWindow?funcapplication(_application:UIApplication,didFinishLaunchingWithOptionslaunchOptions:[UIApplicationLaunchOptionsKey:Any]?)->Bool{ifleturl=Bundle.main.url(forResource:"directory", withExtension: "plist"), let array = NSArray(contentsOf: url) as? [[String:Any]] {
            Shared.instance.employees = array.map{Employee(dictionary: $0)}
        }
        return true
}

I also have this Framework helping me with all of this:

struct EmployeeDetails {
    let functionary: String
    let imageFace: String
    let phone: String

    init(dictionary: [String: Any]) {
        self.functionary = (dictionary["Functionary"] as? String) ?? ""
        self.imageFace = (dictionary["ImageFace"] as? String) ?? ""
        self.phone = (dictionary["Phone"] as? String) ?? ""
    }
}
struct Employee {
    let position: String
    let name: String
    let details: [EmployeeDetails] // [String:Any]

    init(dictionary: [String: Any]) {
        self.position = (dictionary["Position"] as? String) ?? ""
        self.name = (dictionary["Name"] as? String) ?? ""

        let t = (dictionary["Details"] as? [Any]) ?? []
        self.details = t.map({EmployeeDetails(dictionary: $0 as! [String : Any])})
    }
}

struct Shared {
    static var instance = Shared()
    var employees: [Employee] = []
}

So far so good, but I inserted a SearchBar that shows me the correct results, but by touching "Suzan Brown", I see "John Smith" employees . I do not know if the error is in segue ... Could anyone help me? Below, my TableViewController, I know there is something wrong but I do not know exactly what ...

class Page1: UITableViewController, UISearchBarDelegate {

    @IBOutlet weak var searchBar: UISearchBar!

    var employeesSearching = [Employee]()
    var isSearching : Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchBar.delegate = self
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.isSearching == true {
            return self.employeesSearching.count
        } else {
            return Shared.instance.employees.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
        let employee = Shared.instance.employees[indexPath.row]

        if self.isSearching == true {
            cell.nameLabel.text = self.employeesSearching[indexPath.row].name
            cell.positionLabel.text = self.employeesSearching[indexPath.row].position
        } else {
            cell.nameLabel.text = employee.name
            cell.positionLabel.text = employee.position
        }

        return cell
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if self.searchBar.text!.isEmpty {
            self.isSearching = false
            self.tableView.reloadData()
        } else {
            self.isSearching = true
            self.employeesSearching.removeAll(keepingCapacity: false)
            let searchText = self.searchBar.text!.lowercased()
            for employee in Shared.instance.employees {

                if employee.name.lowercased().range(of: searchText) != nil {
                    self.employeesSearching.append(employee)
                }
            }
        }
            self.tableView.reloadData()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? Page2,
            let indexPath = tableView.indexPathForSelectedRow {
            destination.newPage = Shared.instance.employees[indexPath.row]
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
    
asked by anonymous 08.04.2017 / 03:22

2 answers

-1

I solved it!

Just make changes in segue , I'll put the before and after for comparison purposes:

--- BEFORE ---

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? Page2,
        let indexPath = tableView.indexPathForSelectedRow {
        destination.newPage = Shared.instance.employees[indexPath.row]
    }
}

--- AFTER ---

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowP2" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let employee: Employee
            if isSearching == true && searchBar.text != "" {
                employee = employeesSearching[indexPath.row]
            } else {
                employee = Shared.instance.employees[indexPath.row]
            }
            let destination = segue.destination as? Page2
            destination?.newPage = employee
        }
    }
}
    
08.04.2017 / 05:19
1

Place a cell from the cell to the other view. Then take a look at your prepareForSegue function. I recommend creating a custom class for your mobile.

getting something like this:

class CustonTableViewCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var positionLabel: UILabel!

    var employee: Employee? {
        didSet {
            guard let employee = employee else { return }
            nameLabel.text = employee.name
            positionLabel.text = tipoBoleto.descricao
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Returning to the class that has your table, you will now put the data of your prepares for:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowP2" {
        if let cell = sender as? CustonTableViewCell, let employee = cell.employee {
            if let vc = segue.destination as? Page2 {
                // Aqui você passa o objeto que esta em sua cell customizada para a outra tela
                vc.employee = employee
            }
        }
    }
}

Customizing a cell will give you more control over what's being presented.

    
13.04.2017 / 14:45