创建像 iOS 日历一样的表视图

Create tableview like as iOS Calendar

我正在尝试创建一个像 Google 或 iOS 那样的日历。对于日历,我使用了惊人的 FSCalendar。它完美地工作。但是我对日间活动的表格视图有疑问。我用时间轴创建了 uitableview(1 个单元格 = 30 分钟)。但是如何向此处添加看起来像 Google 或 iOS 日历的事件,例如

我想我需要为每个事件添加按钮并将其添加到 uitableview。 这是我的代码:

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (hour_end - hours_begin) * step
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    cell.timeLabel.layer.zPosition = 1
    cell.timeLabel.isHidden = true

    if indexPath.row % step == 0 && indexPath.row != ((hour_end - hours_begin) * step) - 1 {
        let hour = indexPath.row / step + hours_begin
        cell.timeLabel.text = (hour < 10 ? "0": "") + String(hour) + ":00"
        cell.timeLabel.layer.zPosition = 10
        cell.timeLabel.isHidden = false
        cell.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
    }
    else {
        cell.timeLabel.text = ""
        cell.timeLabel.isHidden = true
        cell.separatorInset = UIEdgeInsets(top: 0, left: 2000, bottom: 0, right: 0)
        cell.timeLabel.layer.zPosition = 1
    }

    add_event(indexPath: indexPath, nRef: 5, offset: 0, height: 64.0)

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath.row)
}

func add_event(indexPath: IndexPath, nRef: Int, offset: CGFloat, height: CGFloat)
{
    let row = indexPath.row
    let rectOfCellInTableViewCoordinates = tableView.rectForRow(at: indexPath)
    let rectOfCellInSuperviewCoordinates = view.convert(rectOfCellInTableViewCoordinates, to: tableView.superview)
    print("\(row) \(rectOfCellInSuperviewCoordinates.origin.x) \(rectOfCellInSuperviewCoordinates.origin.y)")
    if row == nRef {
        if let z = view.viewWithTag(nRef) as! UIButton?{
            print("z found")
            z.removeFromSuperview()
        }

        let btn_x = 50
        let btn_width = tableView.frame.width - 50
        let frame = CGRect(x: CGFloat(btn_x), y: rectOfCellInSuperviewCoordinates.origin.y + offset, width: btn_width, height: height)
        let overlay_btn = UIButton(frame: frame)

        overlay_btn.backgroundColor = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 0.3)
        overlay_btn.setTitle("Press for more details", for: .normal)
        overlay_btn.setTitleColor(UIColor.black, for: .normal)
        overlay_btn.layer.cornerRadius = 8
        overlay_btn.tag = 5
        tableView.addSubview(overlay_btn)

    }
}

但是,我认为这不是很好的解决方案。有什么想法吗?

我建议您使用滚动视图来完成您要完成的任务。而不是使用单元格并添加视图......在单元格之间拆分它们将很棘手。相反,您可以拥有包含所有分隔线和小时标记的滚动视图。

实现一个将用作事件的自定义 UIView。当用户创建事件时,它将成为您的滚动视图的子视图。比如说你的滚动视图是 2400px 长,每小时是 100px,如果事件在中午 12 点开始,将 UIView 添加到 1200px 标记...

这是对我将如何处理这个问题的粗略解释。如果您还有其他问题,请随时联系我们。