UITableViewCell 以编程方式设置样式

问题描述 投票:0回答:4

如何使用下一个样式创建 UITableViewCell(xib 中的Right Detail

enter image description here

例如我可以使用下一个:

cell.style = '正确细节'(大致)

谢谢!

ios uitableview
4个回答
25
投票

您想要的是

UITableViewCellStyleValue1
,但您无法设置现有单元格的样式:您必须在创建单元格时进行设置。像这样:

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.