【问题标题】:Pass data between tableViews by using storyboard instantiateviewcontrollerwithidentifier使用 storyboard instantiateviewcontrollerwithidentifier 在 tableViews 之间传递数据
【发布时间】:2017-11-02 20:05:31
【问题描述】:

我正在尝试将数据从一个 tableView 传递到一个静态的。我没有使用segue,而是使用instantiateviewcontrollerwithidentifier,我不知道我哪里出错了。我正在使用 cloudkit 并从 icloud 获取 ckRecords。我首先有一个collectionView,我点击一个单元格并显示与该单元格对应的书籍。但是,当它们显示在单元格中时,我想点击单元格以调出 detailViewController。它目前不起作用,无法弄清楚为什么。

import CloudKit

class DetailViewController: UITableViewController {

    @IBOutlet weak var aboutBookLabel: UILabel!
    @IBOutlet weak var bookLengthLabel: UILabel!
    @IBOutlet weak var amazonPriceLabel: UILabel!
    @IBOutlet weak var ebayPriceLabel: UILabel!
    @IBOutlet weak var websitePriceLabel: UILabel!
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var bookTitleLabel: UILabel!
    @IBOutlet weak var bookImageView: UIImageView!

    var bookRecord: CKRecord?

    override func viewDidLoad() {
        super.viewDidLoad()
        populateData()
    }


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

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor(red: 27.0/255.0, green: 28.0/255.0 , blue: 32.0/255.0, alpha: 1.0)
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    func populateData() {
        aboutBookLabel.text = bookRecord?.object(forKey: "description") as? String
        bookLengthLabel.text = bookRecord?.object(forKey: "length") as? String
        amazonPriceLabel.text = bookRecord?.object(forKey: "amazon") as? String
        ebayPriceLabel.text = bookRecord?.object(forKey: "ebay") as? String
        websitePriceLabel.text = bookRecord?.object(forKey: "authorPrice") as? String
        authorLabel.text = bookRecord?.object(forKey: "author") as? String
        bookTitleLabel.text = bookRecord?.object(forKey: "name") as? String
        if let imageFile = bookRecord?.object(forKey: "image") as? CKAsset {
            bookImageView.image = UIImage(contentsOfFile: imageFile.fileURL.path)
        }

    }
}

class BooksViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    let cellIdentifier = "bookCell"

    var books = [CKRecord]()

    var sectorTitle = "language"

    override func viewDidLoad() {
        super.viewDidLoad()
        registerNib()
        fetchBooksFromCloud()
        configureTableView()
    }

    func fetchBooksFromCloud() {
        books = [CKRecord]()
        books.removeAll()
        tableView.reloadData()

        let cloudContainer = CKContainer.default()
        let publicDatabase = cloudContainer.publicCloudDatabase
        let predicate = buildBookPredicate()
        let query = CKQuery(recordType: "Book", predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        let queryOperation = CKQueryOperation(query: query)
        queryOperation.desiredKeys = ["name", "author", "image", "format", "description", "length", "amazon", "ebay", "authorPrice"]
        queryOperation.queuePriority = .veryHigh
        queryOperation.resultsLimit = 25
        queryOperation.recordFetchedBlock = { (record) -> Void in
            self.books.append(record)
        }
        DispatchQueue.global(qos: .userInteractive).async {
            queryOperation.queryCompletionBlock = { (cursor, error) -> Void in
                if let error = error {
                    print("Download failed \(error.localizedDescription)")
                    return
                }

                print("Download Successful")

                OperationQueue.main.addOperation {
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            }
        }

        queryOperation.qualityOfService = .userInteractive

        publicDatabase.add(queryOperation)
    }

    private func buildBookPredicate() -> NSPredicate {
        return NSPredicate(format:"self contains '\(sectorTitle)'")
    }

extension BooksViewController: UITableViewDelegate, UITableViewDataSource {

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier , for: indexPath) as! BookCell
        let book = books[indexPath.row]
        let bookName = book.object(forKey: "name") as? String
        let authorName = book.object(forKey: "author") as? String
        let image = book.object(forKey: "image") as? CKAsset
        let formatName = book.object(forKey: "format") as? String

        cell.nameLabel.text = bookName
        cell.authorLabel.text = authorName
        cell.formatLabel.text = formatName
        cell.bookImageName.image = UIImage(contentsOfFile: image!.fileURL.path)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let record = books[indexPath.row]
        if let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailVC") as? DetailViewController {
            detailVC.bookRecord = record
            navigationController?.pushViewController(detailVC, animated: true)
        }
        tableView.deselectRow(at: indexPath, animated: true)
    }

【问题讨论】:

  • 目前的结果是什么? DetailViewController 没有显示或显示时没有任何填充数据?
  • @KamilSzostakowski 它只是在if let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailVC") as? DetailViewController 上崩溃。它崩溃并且不显示任何内容。
  • 您确定DetailViewControllerBooksViewController 在同一个故事板上吗?您是否为 DetailViewController 设置了正确的 soryboard id?请发布崩溃消息。
  • @KamilSzostakowski 哦不,不是,它在不同的故事板中。我怎样才能做到这一点。我以为我可以instantiate 它不管
  • 我正在发布答案。

标签: ios swift uitableview cloudkit


【解决方案1】:

UIViewControllerstoryboard 属性表示视图控制器源自的情节提要。如果你想从同一个故事板加载另一个视图控制器,你可以使用它。

但是,如果您想从另一个故事板加载 UIViewController,您必须先创建 UIStoryboard 实例。

你可以这样做。

UIStoryboard(name: "YourStoryboardName", bundle: nil).instantiateViewController(withIdentifier: "DetailVC")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2011-11-02
    相关资源
    最近更新 更多