ios - 如何在另一个 ViewController 中包含 UITableViewCell

标签 ios swift uitableview

我有一个包含 UITableViewCell 的表格 View ,一切正常。但是我需要使用相同的 UITableViewCell 并将其显示在另一个 ViewController 中。这在 iOS 中可能吗?

来自 Android 背景,这可以通过 include 标签轻松完成。在 iOS 中如何实现呢?

最佳答案

如果您打算获取单元格实例并将其显示在另一个 View Controller 中。简短的回答是肯定的,我们可以做到。

UITableViewCell 本质上是一个 UIView,因此没有理由不能将其添加为 UITableView 之外的 subview 。这绝对是一种矫枉过正,因为您可以通过设计自定义 UIView 来实现相同的结果,在其中您可以显示 UITableViewCell 中显示的数据。

这是一个非常基本的示例,说明如何做到这一点。 在此示例中,我们获取包含数据的选定单元格,然后在新的 ViewController 中呈现我们创建的副本。

import UIKit

class ViewController: UITableViewController {

    private let myArray: [String] = ["First","Second","Third"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = OtherViewController()
        vc.cell = tableView.cellForRow(at: indexPath)?.copyView() 
            // notice the .copyView() which makes the copy of that cell
        navigationController?.pushViewController(vc, animated: true)
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
        cell.textLabel!.text = "\(myArray[indexPath.row])"
        return cell
    }
}

class OtherViewController: UIViewController {

    var cell: UITableViewCell! {
        didSet {
            // positioning the cell
            cell.frame.origin.y = 100 // magic number  - remove
            view.addSubview(cell)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

}


//MARK: - UIView Extensions (to make the copy of the cell)

extension UIView {
    func copyView<T: UIView>() -> T {
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
    }
}

关于ios - 如何在另一个 ViewController 中包含 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49242102/

相关文章:

ios - 如何将特定 View 添加到uitableviewcell?

Swift:使用 StoryBoard 在 Tableview 上 float 加号按钮

objective-c - 自定义 UITableViewCell NSUnknownKeyException

iphone - XCode 在 NSData+Base64.m 中标记类型错误

ios - 将点击事件传递给 superview 但处理长按

iphone - CCTouchDispatcher 优先级问题?

ios - 进入信标区域时如何在后台作为信标进行广告

ios - 如何在 RxSwift 中观察 UITableView 点击/选择的先前和当前值?

swift - 如何在 Root View Controller 为 UIViewController 类型的应用程序中弹出到根 Controller ?

ios - BLE 只获取 Battery Level 特征值 IOS