ios - 重用 UITableViewCell 时如何初始化 UI 事物

标签 ios swift uitableview

我想在我的应用程序中重用 UITableViewCell,但我收到此错误:在隐式展开可选值时意外发现 nil。

我发现这是因为 UITableViewCell 中的 UI 东西是 nil,所以我的应用程序崩溃了。

我的UITableViewCell代码是这样的:

class WordListCell: UITableViewCell {

    @IBOutlet weak var wordListCoverImage: UIImageView!
    @IBOutlet weak var wordListName: UILabel!
    @IBOutlet weak var wordListInfo: UILabel!

    var wordList: WordList? {
        didSet {
            updateUI()
        }
    }

    private func updateUI() {
        wordListName.text = wordList?.name
        wordListInfo.text = wordList?.description
        wordListCoverImage = UIImage()
    }
}

我在 storyboard 中创建它,并将 outlet 链接到另一个 TableView 中的代码。

但是这次,我想在一个新的 TableView 中重用单元格,它都是由代码创建的,所以我不知道如何初始化 UI 的东西。

新的UITableView代码是这样的:

tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")

//the delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let wordList = wordLists[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath)
    if let wordListCell = cell as? WordListCell {
        wordListCell.wordList = wordList
    }

    return cell
}

请告诉我如何重用电池。谢谢!

最佳答案

好的,所以我认为您做错的是当您创建自定义 tableView 单元格时,您没有分配 UIImage。因此,请尝试这样做 wordListCoverImage = UIImage(named: wordList.imageName)

除了添加

tableView.delegate = self
tableView.dataSource = self
tableView.register(WordListCell.self, forCellReuseIdentifier: "wordListCell")

然后在 let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath) 将其向下转换为自定义单元格类,如下所示。

let cell = tableView.dequeueReusableCell(withIdentifier: "wordListCell", for: indexPath) as! WordListCell

最后在那个设置下 cell.delegate = self

希望对您有所帮助!

关于ios - 重用 UITableViewCell 时如何初始化 UI 事物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55891802/

相关文章:

ios - 如何在 UITableView 中填充标题单元格

ios - 使用协议(protocol)在 swift 中编写自定义函数

ios - 按下“完成”按钮时 PickerView 不会关闭

ios - 在 Swift 中为 NSMutableAttributedString 设置 kCTUnderlineStyleAttributeName

ios - 当应用程序处于后台时如何在 didReceiveRemoteNotification 上打开特定的 View Controller

ios - 以编程方式创建的 UIControl 中的自动布局似乎不起作用

ios - 为什么 searchBar "textDidChange"获取服务器请求并出错并崩溃

iphone - UITableView部分索引背景?

ios - 在 loadView 方法中计算 View 大小的最佳实践

ios - 如何获取使用 SDWebImage (iOS) 缓存的图像的文件系统路径