想要在主屏幕上显示来自api

时间:2019-06-23 19:55:19

标签: swift xcode textfield searchbar

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

优惠券api的屏幕截图,其中将显示搜索数据: coupons api

搜索api的屏幕截图: search 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:文本字段委托方法 扩展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部分:Int)-> Int {         返回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
    }
}

}

0 个答案:

没有答案