当重用单元格并将UISwitch设置为活动或不活动时,ios listview将第一行和最后一行设置为活动时,出现了什么问题?
我上面的代码应该用我的型号症状填充ios列表:当重用单元格并将UISwitch设置为活动或不活动时,ios listview将第一行和最后一行设置为活动时,出现了什么问题?,ios,swift,uitableview,uiswitch,Ios,Swift,Uitableview,Uiswitch,我上面的代码应该用我的型号症状填充ios列表: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableView.registerNib(UINib(nibName: "SymptomTableCell", bundle: nil), forC
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()
}
这两个是实现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")
从cellforrowatinexpath
,需要进入viewDidLoad()
其次,在您的自定义单元格类中,我将覆盖prepareforeuse
,并将开关设置为关闭状态,然后根据需要在VC中的cellforrowatinexpath
中打开开关,就像您当前的:
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
}
}
1) 不要在
cellforrowatinexpath
内调用registernb
。在viewDidLoad
中执行一次。2) 不要使用dequeueReusableCellWithIdentifier
。使用dequeueReusableCellWithIdentifier:forIndexPath:
。它不能返回nil
单元格。可能是因为您在CellForRowatineXpath中调用了RegisterInB