Переход от пользовательского UITableViewCell к всплывающему представлению с данными - PullRequest
0 голосов
/ 04 июня 2018

У меня есть создание xib как customTableViewCell, и на моей основной раскадровке у меня есть ViewController в качестве всплывающего окна, и я должен связать viewController с всплывающим окном через последовательный способ.Сейчас я пытаюсь открыть всплывающее окно через didSelectRowAt.Когда я запускаю приложение и нажимаю на строку, выдается ошибка

<CustomTableCell.ViewController: 0x7feb4650ea00>) has no segue with  identifier 'popUp'

Ниже мой код

import UIKit
import  os.log


class ViewController: UITableViewController {


    var data = [Response.Recipe]()


    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Restaurants"

        downloadJson()
        tableView.delegate = self
        tableView.dataSource = self

        //tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
        let nib = UINib(nibName: "viewTblCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "customCell")

        if #available(iOS 10.0, *) {
            tableView.refreshControl = refresher
        } else {
            tableView.addSubview(refresher)
        }


//        sampleData()
    }


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

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

        guard let cell: CustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? CustomTableViewCell else {
            os_log("Dequeue cell isn't an instance of CustomTableCell", log: .default, type: .debug)
            fatalError()
        }


        cell.recipeNameLbl?.text = data[indexPath.row].recipeName

        let image = data[indexPath.row].recipeImage
        let ImageUrl = "http://localhost:8888/restaurant/recipeImages/"+image
        if let imageURL = URL(string: ImageUrl) {
            DispatchQueue.global().async {
                let data = try? Data(contentsOf: imageURL)
                if let data = data {
                    let image = UIImage(data: data)
                    DispatchQueue.main.async {
                        cell.recipeImg?.image = image
                    }
                }
            }
        }

        let restaurantOpen = data[indexPath.row].restaurantStatus
        if restaurantOpen == "Closed" {
            cell.restaurantStatusLbl?.text = restaurantOpen
            cell.restaurantStatusLbl?.isHidden = false
        }else{
            cell.restaurantStatusLbl?.isHidden = true
        }

        cell.restaurantOperateDays?.text = data[indexPath.row].restaurantOpenDays
        cell.restaurantOperateTime?.text = data[indexPath.row].restaurantOpenTime
        cell.retaurantNameLbl?.text = data[indexPath.row].restaurantName
        cell.recipeTimeLbl?.text =  "Delivers in " + String(describing: data[indexPath.row].recipeTime) + " minutes"
        cell.recipePriceLbl?.text = "GHS " + String(describing: data[indexPath.row].recipePrice)


        //cell.delegate = self


        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "popUp", sender: self)
        print(data[indexPath.row].recipeName)

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? AddToCartViewController {
            destination.popUpDetails = data[(tableView.indexPathForSelectedRow?.row)!]
        }
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 230
    }



    func downloadJson() {

        let url = URL(string: "http://localhost:8888/restaurant/tableView.php")

        guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil else {
                print("something is wrong")
                return
            }
            print("downloaded")
            do
            {
                let decoder = JSONDecoder()
                let downloadedRecipes = try decoder.decode(Response.self, from: data)
                self.data = downloadedRecipes.recipeTbl

                print(downloadedRecipes.recipeTbl)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            } catch {
                print(error)
            }
            }.resume()
    }

    lazy var refresher: UIRefreshControl = {
        let refreshControl = UIRefreshControl()
        refreshControl.tintColor = UIColor.red
        refreshControl.addTarget(self, action: #selector(requestData), for: .valueChanged)

        return refreshControl

    }()


    @objc func requestData(){
        let deadline = DispatchTime.now() + .milliseconds(800)
        DispatchQueue.main.asyncAfter(deadline: deadline){
            self.downloadJson()
            self.refresher.endRefreshing()
        }
    }
}

1 Ответ

0 голосов
/ 04 июня 2018

Я наконец-то достиг того, что хотел сделать, переместил всплывающее окно на его собственную раскадровку, затем присвоил ему Storyboard ID "addToCart"

Затем я открыл его в методе didSelectRowat

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

        let popup = UIStoryboard(name: "AddToCart", bundle: nil)
        let addToCartPopup = popup.instantiateInitialViewController()! as! AddToCartViewController
        addToCartPopup.popUpDetails = data[(tableView.indexPathForSelectedRow?.row)!]

        self.present(addToCartPopup, animated: true)

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...