gpt4 book ai didi

ios - 在 uitableview 部分组织日期

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:51 25 4
gpt4 key购买 nike

我不知道从哪里开始...我需要一个 TableView 来显示按日期组织的信息。我创建了一个“模型”类来保存数据...

class Model: NSObject {

var start: Date?
var str: String?

override init()
{

}

init(start: Date, str: String) {

self.start = start
self.str = str

}

创建该类的元素

let value1 = Model(start: Date1(), str: string1)
let value2 = Model(start: Date2(), str: string2)

填充该元素的数组:

var array = [Model]()
array.append(value1, value2)

填充TableView我怎样才能划分array,例如分成几个月,或工作周等等......我希望 tableViewsections 中组织数据!?

func numberOfSections(in tableView: UITableView) -> Int {
return array.count
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "January", Febuary, e.g.
return label
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ?
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TC_Arbeitszeit
cell.label.text = ?

return cell
}

非常感谢任何帮助!

最佳答案

使用词典分组功能。您可以将数组组织成键和值,键将是您的部分,而值将是您的原始部分。

按天分组的示例:

extension Date {
var day: Int? {
let components = Calendar.current.dateComponents([.day], from: self)
return components.day
}
}

let array = [model1, model2]

let dict = Dictionary(grouping: array) { (model) -> Int in
return model.start?.day ?? 0
}

例如,模型 1 上“开始”参数的日期是星期日并且 model2 上“开始”参数的日期是星期一

所以 dict 会这样分组:

[1: [model1], 2: [model2]]

现在您可以将键用作部分,将值用作行

func numberOfSections(in tableView: UITableView) -> Int {
return dict.keys ?? 0
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let day = dic.keys[section]
let label = UILabel()
label.text = String(day)
return label
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let key = dict[section]
return dict[key].count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TC_Arbeitszeit
let data = dict[indexPath.section]
cell.label.text = String(data[indexPath.row].start.day)

return cell
}

关于ios - 在 uitableview 部分组织日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154145/

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