在重用单元并设置UISwitch激活或不活动时,ios listview将激活第一行和最后一行,出了什么问题?
问题描述:
我上面的代码应该充满IOS名单与我的模型症状:在重用单元并设置UISwitch激活或不活动时,ios listview将激活第一行和最后一行,出了什么问题?
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
}
}
答
一些事情。从cellForRowAtIndexPath
tableView.registerNib(UINib(nibName: "SymptomTableCell", bundle: nil),
forCellReuseIdentifier: "cell")
,需要在viewDidLoad()
走:首先,在rmaddy评论中提及,删除。
其次,你的自定义单元格类中我会覆盖prepareForReuse
并设置切换到关闭状态,然后将它们作为需要cellForRowAtIndexPath
在你的VC喜欢你目前是:
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)不要打电话'cellForRowAtIndexPath'内的'registerNib'。在'viewDidLoad'中执行一次。 2)不要使用'dequeueReusableCellWithIdentifier'。使用'dequeueReusableCellWithIdentifier:forIndexPath:'。它不能返回一个'nil'单元。 – rmaddy
可能是因为你在cellForRowAtIndexPath里面调用registerNib –