UITableViewCell编程设置样式

10

如何创建带有下一个样式(xib中的右侧详细信息)的UITableViewCell

enter image description here

例如,我可以像这样使用:

cell.style = 'Right Detail' (大致上)

谢谢!


可能会有帮助——https://dev59.com/KmYs5IYBdhLWcg3wDft5 - Rakesha Shastri
4个回答

25

你需要的是 UITableViewCellStyleValue1,但你不能设置一个已存在的单元格的样式:你必须在创建单元格时进行设置。就像这样:

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"YourIdentifier"];

27
如果在tableView上使用dequeueReuseable:forIndexPath:方法会发生什么? - fatuhoku
1
在 initWithStyle 初始化器之外,这该如何完成? - wcochran
这样会行吗?UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:REUSEIDENTIFIER forIndexPath:indexPath]; if(!cell){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:REUSEIDENTIFIER]; } - Mubeen Qazi
@fatuhoku 请查看此链接 https://stackoverflow.com/a/72728320/7734643 - Rakesha Shastri

3

虽然这个问题的最佳答案是正确的,但它没有触及到单元格重用的话题。

事实证明,您不再需要使用tableView.register。相反,您可以使用以下方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // Whenever there's a reusable cell available, dequeue will return it
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") ??
        UITableViewCell(style: .subtitle, reuseIdentifier: "cellIdentifier")

0
如果您想在编程方式下使用UITableViewCell并对其进行样式设置, 则不要将其注册到您的tableView中,而是在cellForRowAt方法中进行设置。
    var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)

    if cell == nil {
       var newCell = UITableViewCell(style: .value1, reuseIdentifier: cellIdentifier)
    // custom styling on textLabel, detailTextLabel, accessoryType
    cell = newCell
   }

注意:deque方法没有IndexPath参数。

0
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "TopCell", for: indexPath)
    cell = UITableViewCell(style: .value1, reuseIdentifier: "TopCell")
            
    var content = cell.defaultContentConfiguration()
    content.text = "Title"
    content.secondaryText = "Detail"
    cell.contentConfiguration = content

    return cell
}

根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,以帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接