gpt4 book ai didi

ios - 一个 UITableView Swift 中的 2 个自定义 UITableViewCell

转载 作者:可可西里 更新时间:2023-11-01 02:19:03 25 4
gpt4 key购买 nike

我正在尝试实现一个自定义表格 View ,它具有不同类型的单元格:A 型和 B 型。我的所有单元格都应该是 A 型,除了一个将是 B 型的单元格。每当用户选择单元格,这个变成 B 型。

我的代码如下:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
if (row == typeBCellIndex) {
// Get Type B cell
let cell = tableView.dequeueReusableCellWithIdentifier(typeBCellIdentifier, forIndexPath: indexPath) as! TypeBTableViewCell
return cell
} else {
// Get Type A cell
let cell = tableView.dequeueReusableCellWithIdentifier(typeACellIdentifier, forIndexPath: indexPath) as! TypeATableViewCell
cell.detailLabel.text = "I am a type A cell"
return cell
}
}

变量 typeBCellIndex 初始化为 0,当我添加新单元格并尝试将索引为 1 的单元格出队时,此代码会出错。

在 Objective-C 中,作为 this links indicates ,我会检查单元格是否为零,如果不是,则创建相应单元格的新实例。但是,我不确定这个概念是否适用于 Swift,如果适用,我不知道该怎么做。

最佳答案

在viewdidload方法之前声明一个变量cellindex并初始化为3或任意数字

并且在tableview中设计两个不同的单元格并为每个单元格分配唯一的标识符

tableview 的代码是

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell : UITableViewCell!
var row = indexPath.row

if(row == cellindex){
cell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! UITableViewCell
}else{
cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
}

return cell
}

cellindex 行将是 cell2,其他单元格是 cell1

关于ios - 一个 UITableView Swift 中的 2 个自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com