gpt4 book ai didi

swift - 单击时在先前的 ViewController 上显示搜索详细数据

转载 作者:行者123 更新时间:2023-11-30 10:40:43 24 4
gpt4 key购买 nike

在我的应用程序中,我有一个自定义搜索栏(即 TextField)来搜索来自 API 的数据。搜索数据显示在 TextField 下方的 TableView 中。

当我点击搜索结果时,它应该在 ViewController`即我的 homecontroller 文件中显示其详细数据

enter image description here

enter image description here

搜索 Controller 代码:

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()

}

}

主页 Controller ,我希望在其中显示搜索到的数据:

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
}
}
}

最佳答案

在您的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)
}

然后在您的 SearchPageControllertableView: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
}

关于swift - 单击时在先前的 ViewController 上显示搜索详细数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56842026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com