Показать детальные данные поиска на предыдущем ViewController при нажатии - PullRequest
0 голосов
/ 01 июля 2019

В моем приложении есть пользовательская панель поиска (например, TextField) для поиска данных, поступающих из API. Данные поиска отображаются в TableView ниже TextField.

Когда я нажимаю на результат поиска, он должен показывать свои подробные данные в файле ViewController`.i.e моего homecontroller

enter image description here

enter image description here

Код контроллера поиска:

class SearchPageController: UIViewController {

    @IBOutlet weak var searchTxtBar: UITextField!
    @IBOutlet weak var searchTblView: UITableView!

    var searchData = [ModelSearched]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()

        // Do any additional setup after loading the view.
        searchTxtBar.delegate = self

    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    //MARK: IBActions
    @IBAction func toHomeScreen(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }

    func getSearchList(){

        let params: Parameters=[
            "search":"\(self.searchTxtBar.text ?? "")",
        ]

        if ApiUtillity.sharedInstance.isReachable()
        {
            ApiUtillity.sharedInstance.StartProgress(view: self.view)
            APIClient<ModelBaseSearchList>().API_GET(Url: SD_GET_SearchList, Params: params as [String:AnyObject], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

                ApiUtillity.sharedInstance.StopProgress(view: self.view)

                if(modelResponse.success == true) {

                    if self.searchTxtBar.text!.count != 0 {
                       self.searchData.removeAll()
                    }

                    let resul_array_tmp_new = modelResponse.searched! as NSArray

                    if resul_array_tmp_new.count > 0 {
                        for i in modelResponse.searched! {
                            self.searchData.append(i)
                        }
                    }
                }
                else {
                    self.view.makeToast(modelResponse.message)
                }
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
                self.searchTblView.reloadData()
            }) { (failed) in
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
                self.view.makeToast(failed.localizedDescription)
            }
        }
        else
        {
            self.view.makeToast("No Internet Connection..")
        }
    }

    @IBAction func clearSearchData(_ sender: UIButton) {

        self.searchData.removeAll()
        self.searchTxtBar.text = ""
        searchTblView.reloadData()
    }

}

//MARK: Tableview delegates and datasource methods
extension SearchPageController: UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        if searchData.count == 0 {

            tableView.setEmptyView(message: "Try searching categories/store data..", messageImage: UIImage(named: "magnifier")!)

        }else {
            tableView.restore()
        }

        return searchData.count
    }

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

        var cell = tableView.dequeueReusableCell(withIdentifier: "catstoredata")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "catstoredata")
        }
        let dict = searchData[indexPath.row]
        cell?.selectionStyle = .none
        cell?.textLabel?.text = dict.name

        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        self.navigationController?.popViewController(animated: true)
    }
}

//MARK: textfield delegates method
extension SearchPageController: UITextFieldDelegate{

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        self.searchTxtBar.resignFirstResponder()
        self.searchTblView.reloadData()
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        self.getSearchList()

    }

}

Контроллер домашней страницы, где я хочу отображать искомые данные:

class HomeViewController: UIViewController {

    var couponsData = [ModelCoupons]()
    var colorList = [UIColor]()
    var selectedIds = [Int]()

    @IBOutlet var logoutPopup: UIView!
    @IBOutlet weak var homeTblView: UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        //append colors

        colorList.append(UIColor(rgb: 0xdd191d))
        colorList.append(UIColor(rgb: 0xd81b60))
        colorList.append(UIColor(rgb: 0x8e24aa))
        colorList.append(UIColor(rgb: 0x5e35b1))
        colorList.append(UIColor(rgb: 0x3949ab))
        colorList.append(UIColor(rgb: 0x4e6cef))
        colorList.append(UIColor(rgb: 0x00acc1))
        colorList.append(UIColor(rgb: 0x00897b))
        colorList.append(UIColor(rgb: 0x0a8f08))
        colorList.append(UIColor(rgb: 0x7cb342))
        colorList.append(UIColor(rgb: 0xc0ca33))
        colorList.append(UIColor(rgb: 0xfdd835))
        colorList.append(UIColor(rgb: 0xfb8c00))
        colorList.append(UIColor(rgb: 0xf4511e))
        colorList.append(UIColor(rgb: 0xf4511e))
        colorList.append(UIColor(rgb: 0x757575))
        colorList.append(UIColor(rgb: 0x546e7a))

        self.homeTblView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
        self.homeTblView.register(UINib(nibName: "Home1Cell", bundle: nil), forCellReuseIdentifier: "Home1Cell")

        self.post_CouponsData()
        self.homeTblView.reloadData()
        print(selectedIds)

    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    func changeDateForamte(dateString: String, currentDateFormate: String, newDateFormate: String) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = currentDateFormate
        let newDate = dateFormatter.date(from: dateString)
        dateFormatter.dateFormat = newDateFormate
        return  dateFormatter.string(from: newDate!)
    }

    @IBAction func logout_yes(_ sender: Any) {
        Defaults.remove(.udk_IS_LOGIN)
       let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }

    @IBAction func logout_no(_ sender: Any) {
       self.logoutPopup.removeFromSuperview()
    }

    @objc func openDeals(sender: UIButton) {

        if sender.tag == 12 {

            DispatchQueue.global().async {

                let svc = SFSafariViewController(url: URL(string: self.couponsData[sender.tag].subUrl!)!)
                self.present(svc, animated: true, completion: nil)

                DispatchQueue.main.async(execute: {

                     let svc = SFSafariViewController(url: URL(string: self.couponsData[sender.tag].guid!)!)
                    self.present(svc, animated: true, completion: nil)
                })
            }

        }else {
            DispatchQueue.global().async {

                let svc = SFSafariViewController(url: URL(string: self.couponsData[sender.tag].subUrl!)!)
                self.present(svc, animated: true, completion: nil)

                DispatchQueue.main.async(execute: {

                    let svc = SFSafariViewController(url: URL(string: self.couponsData[sender.tag].guid!)!)
                    self.present(svc, animated: true, completion: nil)
                })
            }
        }
    }

    //MARK: IBActions
    @IBAction func toCategoryScreen(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }

    @IBAction func toSearchPage(_ sender: UIButtonX) {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SearchPageController") as! SearchPageController
        self.navigationController?.pushViewController(vc, animated: true)
    }

    @IBAction func logoutBtnPressed(_ sender: Any) {
        ApiUtillity.sharedInstance.AddSubViewtoParentView(parentview: self.view, subview: logoutPopup)
    }

    func post_CouponsData() {
        if ApiUtillity.sharedInstance.isReachable() {

            var params = [String : String]()

            params ["term_ids"] = "\(self.selectedIds.map(String.init).joined(separator: ","))"

            ApiUtillity.sharedInstance.StartProgress(view: self.view)

            APIClient<ModelBaseCouponsList>().API_POST(Url: SD_POST_CouponsList, Params: params as [String:AnyObject], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

                ApiUtillity.sharedInstance.StopProgress(view: self.view)

                if(modelResponse.success == true) {

                    ApiUtillity.sharedInstance.StopProgress(view: self.view)

                    let dict = modelResponse.coupons
                    for i in dict! {
                        self.couponsData.append(i)
                    }

                }else {
                    self.view.makeToast(modelResponse.message)
                }
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
                self.homeTblView.reloadData()

            }) { (failed) in
                self.view.makeToast(failed.localizedDescription)
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
            }
        }else {
            self.view.makeToast("No internet connection...")
            ApiUtillity.sharedInstance.StopProgress(view: self.view)
        }
    }
}


extension HomeViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return couponsData.count
    }

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

        let couponObj = couponsData[indexPath.row]

        if couponObj.postImage!.count != 0 {

            if couponObj.subUrl!.isEmpty {

                let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let path = Bundle.main.path(forResource: "loader1", ofType: "gif")!
                let data = try! Data(contentsOf: URL(fileURLWithPath: path))

                cell.home_image.kf.indicatorType = .image(imageData: data)
                cell.home_image.kf.setImage(with: URL(string: couponObj.postImage!), placeholder: UIImage(named: "placeholder"), options: [.transition(.fade(0.2))])

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")


                if let couponTitle = couponObj.coupon_code, couponTitle.count != 0 {

                    cell.couponView.isHidden = false
                    cell.seeproductView.isHidden = false
                    cell.goToDealBtn.isHidden = true
                    cell.couponTitle.text = couponObj.coupon_code
                }else {

                    cell.couponView.isHidden = true
                    cell.seeproductView.isHidden = true
                    cell.goToDealBtn.isHidden = false
                    cell.couponTitle.text = "N/A"
                }


                cell.seeProductBtnTapped.tag = 12
                cell.seeProductBtnTapped.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell

            }else if couponObj.subUrl!.isEmpty && couponObj.coupon_code!.isEmpty {

                let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let path = Bundle.main.path(forResource: "loader1", ofType: "gif")!
                let data = try! Data(contentsOf: URL(fileURLWithPath: path))

                cell.home_image.kf.indicatorType = .image(imageData: data)
                cell.home_image.kf.setImage(with: URL(string: couponObj.postImage!), placeholder: UIImage(named: "placeholder"), options: [.transition(.fade(0.2))])

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

                cell.couponView.isHidden = true
                cell.seeproductView.isHidden = true
                cell.goToDealBtn.isHidden = false

                cell.goToDealBtn.tag = 13
                cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell

            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let path = Bundle.main.path(forResource: "loader1", ofType: "gif")!
                let data = try! Data(contentsOf: URL(fileURLWithPath: path))

                cell.home_image.kf.indicatorType = .image(imageData: data)
                cell.home_image.kf.setImage(with: URL(string: couponObj.postImage!), placeholder: UIImage(named: "placeholder"), options: [.transition(.fade(0.2))])

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

                cell.couponView.isHidden = true
                cell.seeproductView.isHidden = true
                cell.goToDealBtn.isHidden = false

                cell.goToDealBtn.tag = 13
                cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell
            }


        } else {

            if couponObj.subUrl!.isEmpty {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Home1Cell", for: indexPath) as! Home1Cell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")


                if let couponTitle = couponObj.coupon_code, couponTitle.count != 0 {

                    cell.couponView.isHidden = false
                    cell.seeproductView.isHidden = false
                    cell.goToDealBtn.isHidden = true
                    cell.couponTitle.text = couponObj.coupon_code
                }else {

                    cell.couponView.isHidden = true
                    cell.seeproductView.isHidden = true
                    cell.goToDealBtn.isHidden = false
                    cell.couponTitle.text = "N/A"
                }

                cell.seeProductBtnTapped.tag = 12
                cell.seeProductBtnTapped.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell

            } else if couponObj.subUrl!.isEmpty && couponObj.coupon_code!.isEmpty{

                let cell = tableView.dequeueReusableCell(withIdentifier: "Home1Cell", for: indexPath) as! Home1Cell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

                cell.couponView.isHidden = true
                cell.seeproductView.isHidden = true
                cell.goToDealBtn.isHidden = false

                cell.goToDealBtn.tag = 13
                cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell

            }else {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Home1Cell", for: indexPath) as! Home1Cell

                if let postTitle = couponObj.postTitle, postTitle.count != 0 {
                    cell.ticket_postTitle.text = postTitle
                }
                if let postContent = couponObj.postContent, postContent.count != 0 {
                    cell.ticket_postContent.text = postContent
                }

                let randomInt = Int(arc4random()) % colorList.count
                cell.ticketImageView.tintColor = colorList[randomInt]

                cell.ticket_ValidDate.text = self.changeDateForamte(dateString: couponObj.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

                cell.couponView.isHidden = true
                cell.seeproductView.isHidden = true
                cell.goToDealBtn.isHidden = false

                cell.goToDealBtn.tag = 13
                cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
                return cell

            }

        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let vc = self.storyboard?.instantiateViewController(withIdentifier: "CouponDetailVC") as! CouponDetailVC
        let indexPath = tableView.indexPathForSelectedRow
        vc.couponData = couponsData[indexPath!.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        let couponObj = couponsData[indexPath.row]

        if couponObj.postImage!.count != 0 {
            return 334.0
        }else {
            return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

        let couponObj = couponsData[indexPath.row]

        if couponObj.postImage!.count != 0 {
            return 334.0
        }else {
            return UITableView.automaticDimension
        }
    }
}

1 Ответ

0 голосов
/ 03 июля 2019

В вашем SearchPageController , сделайте ниже функцию.

func gotoHomeVC(_ data: Int) {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
    if !vc.selectedIds.isEmpty {
        vc.selectedIds.removeAll()
    }
    vc.selectedIds.append(data)
    self.navigationController?.pushViewController(vc, animated:true)
}

Затем в вашем SearchPageController * tableView: didSelectRowAtIndexPath: замените ваши коды следующим кодом:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath {
    tableView.deselectRow(at: indexPath, animated: true)
    guard let data = searchData[indexPath.row].iD else {return}
    self.gotoHomeVC(data) // call the function here
}
...