ios - 上次单击时如何使按钮 UIButton 保存

标签 ios swift realm

基本上我正在尝试制作一个习惯跟踪器应用程序。我仍在试图弄清楚如何在最后一次单击时保存单元格。我正在使用 RealmSwift

这是我想实现的功能


        func setupDateAndTIme(btnCheckMark: UIButton) {

            let elapsedTime = NSDate().timeIntervalSince(habit.updatedAt as Date)
            let duration = Int(elapsedTime)
            let waitingTime = 45
            //change waiting time to 43200 for actual app but test w 60 smtn
            if duration < waitingTime && habit.checked == true {
                btnCheckMark.setBackgroundImage(UIImage(named: "checkedOff"), for: UIControl.State.normal)
                btnCheckMark.isEnabled = false
            } else {
                btnCheckMark.setBackgroundImage(UIImage(named: "emptyCheckbox"), for: UIControl.State.normal)
                btnCheckMark.isEnabled = true
            }

        }



当我以编程方式制作这个应用程序时,这是表格 View 功能

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListIdentifier") as! CheckMarkCell

        cell.btnCheckMark.addTarget(self, action: #selector(checkMarkButtonClicked(sender:)), for: .touchUpInside)

        cell.textLabel!.text = "\(myArray[indexPath.row])"
        return cell
    }
   @objc func checkMarkButtonClicked ( sender: UIButton) {
        print("button presed")

        if sender.isSelected {
            //uncheck the butoon
            sender.isSelected = false

        } else {
            // checkmark it
            sender.isSelected = true

        }

    }


这是单元格的代码
class CheckMarkCell: UITableViewCell {
    let habit = Habit()
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var btnCheckMark: UIButton!

}

有人能告诉我如何实现这个功能吗?谢谢你!

最佳答案

  • 将 View Controller 的弱引用添加到单元格中
  • 点击按钮时调用 View Controller 中的一些方法
  • 更新选择按钮的标志,例如var selectedIndexes = [Int]()其中 index 是带有按钮
  • 的单元格的行号
  • 重新加载表格中的单元格或立即更新按钮状态。
  • @objc func checkMarkButtonClicked必须是单元格的一部分。

    逻辑:user --tap--> cell --call_vc.updateButtonState()--> vc [saves flag] --tableView_reloadCell-->

    关于ios - 上次单击时如何使按钮 UIButton 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918386/

    相关文章:

    ios - 使用 Realm 的 RLMArray 存储字符串数组

    ios - 尝试使用 Realm 对象服务器教程

    ios - 创建每个用户唯一的密码,其他用户无法使用

    iphone - 使用 CoreData 创建新闻提要

    iphone - 在 iOS 中将 Unity 生成的代码与 Objective-C 混合?

    swift - 为 Socrate 数据集查询构造 URL,其中日期大于日期

    arrays - 创建除一项之外的所有项目循环以应用效果

    iphone - UIPopoverController 在没有委托(delegate)调用的情况下解散

    ios - UIView 框架在 traitCollectionDidChange 期间未更新

    android - 在主应用程序和库中使用 Realm