在Swift中使用UITableView
及其UITableViewCell
。我在显示一个detailTextLabel
字段时遇到了一些问题。
我已经找到了这两个有用的帖子,但没有找到一个完全有效的解决方案:swift detailTextLabel not showing up How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?。
下面是我使用的与我的问题相关的代码:
override func viewDidLoad() {
super.viewDidLoad()
………….
theTableView = UITableView(frame: tmpFrame)
………….
theTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
theTableView.dataSource = self
theTableView.delegate = self
self.view.addSubview(theTableView)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = "THE-TEXT-LABEL"
cell.detailTextLabel?.text = "KIJILO" // This does not show up.
return cell
}
当我尝试使用detailTextLabel
字段UITableViewCell
时,它不会出现。在网络上搜索时,我知道我必须为单元格使用适当的样式(UITableViewCellStyle
),但我不知道如何将该更改集成到代码中。我看到的示例是基于子类UITableViewCell
的,我想我不需要只对UITableViewCell
子类进行子类来使用detailTextLabel
字段。如果我错了,请告诉我。
我也从上面提到的帖子中尝试了一些东西,但是没有任何东西能像我想要的那样工作。
发布于 2015-12-05 04:22:58
你已经注册了UITableViewCell
theTableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "reuseIdentifier")
这意味着当你打电话
tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
forIndexPath: indexPath)
其中一个将自动使用UITableViewCellStyleDefault样式为您创建。
因为你想要一种定制的风格,所以你需要做一些事情:
删除
theTableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "reuseIdentifier")
替换
var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
forIndexPath: indexPath)
使用以下内容
var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier")
if cell == nil {
cell = UITableViewCell(style: .Value1, reuseIdentifier: "reuseIdentifier")
}
这里发生的情况是,如果dequeueReusableCellWithIdentifier
不能对单元格进行排队列,它将返回零。然后,您可以生成具有指定样式的自己的单元格。
发布于 2021-03-10 08:10:10
如果您使用的是Storyboard
Subtitle
发布于 2019-09-26 18:20:14
我发现只检查cell
是否为nil.
是不够的,我添加了这个附加检查:
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
if cell == nil || cell?.detailTextLabel == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellReuseIdentifier)
}
https://stackoverflow.com/questions/34101102
复制相似问题