首页 > 解决方案 > 关于在 Swift 中设置闹钟日期的问题

问题描述

我正在制作类似于 iPhone 闹钟应用程序的闹钟功能。

设置闹钟日期时,我正在编写代码来检查星期几。

class DaySelectCell: UITableViewCell {

    @IBOutlet weak var dayLbl: UILabel!
    @IBOutlet weak var checkView: Checkbox!
}
import UIKit

class DaySelectViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    let days = ["일요일마다","월요일마다","화요일마다","수요일마다","목요일마다","금요일마다","토요일마다"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }
}

extension DaySelectViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return days.count
    }

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

        cell.dayLbl.text = days[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DaySelectCell") as! DaySelectCell
    }
}

我想问的部分是当我单击某个日期单元格时,didSelectRowAt 我想制作checkView.isSelectd那个单元格。true

在此处输入图像描述

标签: iosswift

解决方案


您必须管理数据源以保存所选值,因此您可以假装选择了哪个索引。

var selectedDays: [Int] = []

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   cell.accessoryType = selectedDays.contains(indexPath.row) ? .checkmark : .none
}

现在在didSelectRowAt方法中编写此代码

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let index = selectedDays.firstIndex(where: { $0 == indexPath.row }) {
        selectedDays.remove(at: index)
    } else {
        selectedDays.append(indexPath.row)
    }
    tableView.reloadData()
}

推荐阅读