ios - 在 uitableview 部分组织日期

标签 ios swift tableview

我不知道从哪里开始... 我需要一个 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/

相关文章:

ios - 在 iPad Pro 上放大的 iPad Air App

ios - 工作日字符串如何通过传递整数从 NSDateComponents 返回?

ios - iphone plus中的Swift奇怪的后退按钮文本

python - 客户端 服务器端实时物体检测

iphone - TableViewDataSource 文件的运行时错误已分离

ios - 如何在使用 NSUserDefaults 重新加载 View 后保存 tableView 单元格的复选标记?

ios - MPMusicPlayerController音量衰减

android - Kotlin 多平台项目

ios - 按下时更改表格 View 中项目的颜色

ios - 在表 IOS 中选择单元格