首页 > 解决方案 > 想要在主屏幕上显示来自 api 的搜索数据的数据

问题描述

我正在制作一个应用程序,其中有一个主屏幕,其中列出了类别并将数据存储到 tableview 中。在tableview中,我有一个搜索按钮,单击该按钮可将我导航到搜索屏幕,并且在搜索屏幕上,我已使用自定义文本字段进行搜索。现在我希望当我搜索某些内容并显示在结果中时,然后当我单击搜索结果时,它应该显示在前一个主屏幕上选择的类别或商店的数据。搜索结果是类别数据和商店数据。所有数据都来自 api 并且正在使用 tableview 来显示搜索数据

将显示搜索数据的优惠券 api 的屏幕截图: 优惠券API

搜索 api 的屏幕截图: 搜索接口

我的搜索屏幕的代码如下:

类 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":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) {

                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 委托和数据源方法扩展 SearchPageController: UITableViewDelegate, UITableViewDataSource{

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

   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 委托方法扩展 SearchPageController: UITextFieldDelegate{

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

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

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

}

}

我的主屏幕的代码如下:

类 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) {
   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) {
    let svc = SFSafariViewController(url: URL(string: 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)
    }
}

}

扩展 HomeViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return couponsData.count }

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


    if !couponsData[indexPath.row].postImage!.isEmpty {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
        let dict = couponsData[indexPath.row]

        if let postTitle = dict.postTitle, postTitle.count != 0 {
            cell.ticket_postTitle.text = postTitle
        }
        if let postContent = dict.postContent, postContent.count != 0 {
            cell.ticket_postContent.text = postContent
        }
        if let storeName = dict.stores, storeName.count != 0 {
            cell.storename.text = storeName
        }

        cell.home_image.image = UIImage(named: dict.postImage!)
        cell.ticketImageView.tintColor = colorList[indexPath.row]
        cell.ticket_ValidDate.text = self.changeDateForamte(dateString: dict.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

        //        cell.ticketImageView.tintColor = .random()
        cell.goToDealBtn.tag = indexPath.row
        cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
        return cell
    }else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Home1Cell", for: indexPath) as! Home1Cell
        let dict = couponsData[indexPath.row]

        if let postTitle = dict.postTitle, postTitle.count != 0 {
            cell.ticket_postTitle.text = postTitle
        }
        if let postContent = dict.postContent, postContent.count != 0 {
            cell.ticket_postContent.text = postContent
        }
        if let storeName = dict.stores, storeName.count != 0 {
            cell.storename.text = storeName
        }

        cell.ticketImageView.tintColor = colorList[indexPath.row]
        cell.ticket_ValidDate.text = self.changeDateForamte(dateString: dict.validTill!, currentDateFormate: "yyyy-MM-dd", newDateFormate: "dd MMMM yyyy")

        //        cell.ticketImageView.tintColor = .random()
        cell.goToDealBtn.tag = indexPath.row
        cell.goToDealBtn.addTarget(self, action: #selector(self.openDeals), for: .touchUpInside)
        return cell
    }


}

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

    if !couponsData[indexPath.row].postImage!.isEmpty {
       return 339.0
    }else {
        return 234.0
    }

}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    if !couponsData[indexPath.row].postImage!.isEmpty {
        return 339.0
    }else {
        return 234.0
    }
}

}

标签: swiftxcodetextfieldsearchbar

解决方案


推荐阅读