ios - 使用 Storyboard instantiateviewcontrollerwithidentifier 在 tableView 之间传递数据

标签 ios swift uitableview cloudkit

我正在尝试将数据从一个 tableView 传递到一个静态 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)
    }

最佳答案

UIViewControllerstoryboard 属性表示 View Controller 起源的 Storyboard。如果你想从同一个 Storyboard加载另一个 View Controller ,你可以使用它。

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

你可以这样做。

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

关于ios - 使用 Storyboard instantiateviewcontrollerwithidentifier 在 tableView 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083755/

相关文章:

ios - 获取某个位置的最新消息

ios - React-Native + Flex 不响应方向变化

ios - 如何在 Swift 中覆盖和使用 alloc?

ios - 即使在删除某些单元格后,仍以与 TableView Cell 相同的顺序将文本字段值保存在数组中

swift - 在 Promisekit 完成运行并在 Swift 中返回正确的值之前循环递增并重新运行

ios - 在 iOS 11 上将 insetsContentViewsToSafeArea 设置为 false 的 iPhone X 上,UITableView 单元格不会从屏幕的边缘延伸到屏幕的边缘

ios - 从 UITableViewCell 更新 UIViewController 中数组的对象

iphone - TTTableViewController 用对象数组变量填充数据源

ios - 自定义 PageControl 图像 - Swift

ios - 当键盘弹起并且有一行时聚焦到底部单元格