首页 > 解决方案 > 使用自定义 UITableViewCells 并使用 Swift 数组复制它们

问题描述

我正在开发一个 iOS 应用程序,我有一个基于数组UITableView生成s 的应用程序。UITableViewCell

换句话说,我有一个自定义单元格,里面有UIViews。如何添加一个包含 Repo 标签文本和 URL 标签文本的二维数组,并生成大量带有array.count.

我的自定义 UITableViewCell

这是我的代码:

class SourcesViewController: UITableViewController {

    var array:[[String]] = [["Thunderbolt iOS Utilities", "https://repo.thunderbolt.semiak.dev"], ["Semiak's Repo", "repo.semiak.dev"]]

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        //How can I setup all the arguments my custom UITableViewCell needs?
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


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

对不起,如果解释真的很糟糕,我以前从未做过这件事,而且我是 iOS 开发的新手,所以我不知道如何准确地解释我需要什么。

标签: iosswiftuitableview

解决方案


这是一个起点(我不建议将此代码用于生产。有更好的方法(例如,使用结构数组,将代码放入自定义单元格等))

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let dataArray = array[indexPath.row] // get the data for the cell
    // not a great idea but....
    cell.repoLabel.text = dataArray.first ?? ""
    cell.urlLabel.text = dataArray.last ?? ""
    return cell
}

推荐阅读