【问题标题】:custom tableview controller's cell text自定义 tableview 控制器的单元格文本
【发布时间】:2017-09-04 13:19:56
【问题描述】:

我有一个自定义的 tableview 控制器,它有 3 个部分。

第一个部分有一个集合视图。 现在我想在第二部分的第一个单元格中添加文本(长度小于 1000 个字符)。

我打算将单元格样式设为基本样式,以便添加标题。

  1. 如何拨打cell.title.text = myString

我的意思是我想要类似的东西

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView.section == 2 and cell == 1 {
        cell.title.text = myString
        return cell
    }
}
  1. 因为myString长度在0~1000字之间。如何根据myString 的长度更改单元格的高度?

谢谢

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

第一个问题

首先为单元格设置一个标识符。如果您正在使用情节提要,请在选择单元格时在 Attributes Inspector 的 Identifier 字段中输入一个值。

假设您将该标识符设置为"basic"。然后编写类似以下代码:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 1 && indexPath.row == 0 {
        // Section and row numbers start from 0, like practically everything else
        // in Cocoa, so 1 is the second section, and 0 is the first row.
        let cell = tableView.dequeueReusableCell(withIdentifier: "basic")! // Get a cell from the table view
        cell.textLabel?.text = myString // Set the string
        return cell
    }
}

第二个问题

要允许文本字段在字符串较长时增加高度,只需将单元格中标签的numberOfLines 属性设置为一个大数字(或您根据字符串长度以某种方式计算的数字)。例如,在上面的方法中,在return cell之前,插入这一行:

cell.textLabel?.numberOfLines = 1000

根据其文档,numberOfLines 属性是用于呈现文本的最大行数,因此将其设置为非常大的数字应该没有什么问题。它仍然会根据字符串的长度调整大小。

【讨论】:

  • 如果有条件,我需要将单元格返回到外部。
  • @John 暂时,要测试我的代码,请尝试在 if 块之外添加 return UITableViewCell()。这将暂时修复错误。
  • 我收到此错误致命错误:在展开可选值时意外发现 nil
  • @John 这将是由于调用tableView.dequeueReusableCell(withIdentifier:) 后强制展开。您确定在情节提要中正确设置了单元格的标识符吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多