ios - 在重用单元格并设置 UISwitch 是否处于事件状态时,ios listview 将第一行和最后一行设置为事件状态,有什么问题?

标签 ios swift uitableview uiswitch

我上面的代码应该用我的模型症状填充 ios 列表:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
    UITableViewCell {
        tableView.registerNib(UINib(nibName: "SymptomTableCell", bundle: nil),
                              forCellReuseIdentifier: "cell")

        if let cell = tableView.dequeueReusableCellWithIdentifier("cell")
            as? SymptomTableCell {
            print(indexPath.row)
            print(cell)
            let symptom = symptoms[indexPath.row]
            if Editor.isEditing {
                cell.setDatasource(symptom, isSelected:
                    hasSymptom(symptomsEdit, oid: symptom.oid))
            } else {
               cell.setDatasource(symptom, isSelected: cell.swItem.on)
            }
            cell.tag = Helper.random()
            cell.backgroundColor = UIColor.clearColor()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            tableCells.append(cell)
            return cell
        }
    return UITableViewCell()
}

first cell

last cell

这两个是我实现 UITableView 的对象你可以看到附加的图像来理解错误:

import Foundation
import EVReflection

class Symptom: EVObject {
    var oid = ""
    var name = ""
}


import UIKit

class SymptomTableCell: UITableViewCell {

    var symptom: Symptom?
    @IBOutlet weak var swItem: UISwitch!
    @IBOutlet weak var lblItem: UILabel!

    func setDatasource(symptom: Symptom, isSelected: Bool) {
        self.symptom = symptom
        lblItem.text = symptom.name
        swItem.on = isSelected
    }
}

最佳答案

一些事情。首先,正如 rmaddy 在评论中提到的那样,删除:

tableView.registerNib(UINib(nibName: "SymptomTableCell", bundle: nil),
                          forCellReuseIdentifier: "cell")

来自cellForRowAtIndexPath,需要进入viewDidLoad()

其次,在您的自定义单元格类中,我将覆盖 prepareForReuse 并将开关设置为关闭状态,然后根据需要在您的 VC 中的 cellForRowAtIndexPath 中打开它们,就像您目前是:

class SymptomTableCell: UITableViewCell {

    var symptom: Symptom?
    @IBOutlet weak var swItem: UISwitch!
    @IBOutlet weak var lblItem: UILabel!

    override func prepareForReuse() {
         self.swItem.setOn(false, animated: false)
    }

    func setDatasource(symptom: Symptom, isSelected: Bool) {
        self.symptom = symptom
        lblItem.text = symptom.name
        swItem.on = isSelected
    }

}

关于ios - 在重用单元格并设置 UISwitch 是否处于事件状态时,ios listview 将第一行和最后一行设置为事件状态,有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40161724/

相关文章:

ios - 在 swift iOS 中使用 uipickerview 的 uialertcontroller?

ios - TableView 单元格在单个表中按列或按行显示列表

ios - 从 UITableViewController 的 View 模型呈现模态

ios - 如何在 Swift 4 中保留 Realm List 属性?

ios - 当查询参数包含&符号时编码 NSURL

swift - 为什么在 Playground 中运行时调度的 print() 的顺序会改变?

ios - 在受限制的 UIScrollView 中嵌入 UITableView 和其他 UIView

iphone - 粒子效果类似于 chillingo 的碰撞效果

ios - 将 [NSDate date] 转换为本地化的 UTC 日期字符串

ios - 一种在每次快速运行时重新加载 ViewDidLoad 的方法