我的 TableView 里面有 3 个 TableViewCell。
- 第一个 TableViewCell 有:标签
- 第二个 TableViewCell 有:TextField
- 第三个 TableViewCell 有:按钮
我的问题是你想为每个人设置不同的重复次数。
例如,我希望第一个 tableViewCell 重复 3 次,第二个 tableViewCell 重复 2 次,第三个 tableViewCell 重复 2 次。
TableView 将是这样的:
- 标签
- 标签
标签
文本字段
文本字段
按钮
- 按钮
我的代码:
import UIKit
class FilterPage: UIViewController, UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let PropertTypeCell = tableView.dequeueReusableCell(withIdentifier: "PropertyTypeCell")
return PropertTypeCell!
} else if indexPath.row == 1{
let PriceCell = tableView.dequeueReusableCell(withIdentifier: "PriceCell")
return PriceCell!
}
else{
let RoomCell = tableView.dequeueReusableCell(withIdentifier: "RoomCell")
return RoomCell!
}
}
}
最佳答案
对于这种情况,我喜欢制作一个 CellTypes
数组,在这种情况下我定义了一个枚举类型 CellType
enum CellType {
case PropertyTypeCell
case PriceCell
case RoomCell
}
然后在一个方法中,如果你想要动态的,我填充一个 CellType
数组,在你的情况下你可以使用这样的初始化
var cellTypes : [CellType] = [.PropertyTypeCell,.PropertyTypeCell,.PropertyTypeCell,.PriceCell,.PriceCell,.RoomCell,.RoomCell]
在此之后,您可以返回您的numberOfRowsInSection
方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellTypes.count
}
最重要的是你可以忘记 IndexPath 的噩梦,只需要获取当前的 CellType
你就可以做这样的事情
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let celltype = self.cellTypes[indexPath.row]
switch celltype {
case .PropertyTypeCell:
let PropertTypeCell = tableView.dequeueReusableCell(withIdentifier: "PropertyTypeCell")
return PropertTypeCell!
case .PriceCell:
let PriceCell = tableView.dequeueReusableCell(withIdentifier: "PriceCell")
return PriceCell!
default:
let RoomCell = tableView.dequeueReusableCell(withIdentifier: "RoomCell")
return RoomCell!
}
}
此方法允许您更改表结构,而无需触及您的 cellForRowAtIndexPath 方法,也无需考虑您的 indexpaths.rows 数字,这可能非常棘手
关于ios - 如何为每个 TableViewCell 添加具有不同重复次数的 Multiple TableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394299/