【发布时间】:2019-01-05 13:23:12
【问题描述】:
我正在创建一个带有自定义单元格的测验应用程序,其中包含问题标签和来自 UISegmentedControl 的答案。
segmentedcontrols 的值在滚动时会发生变化,这会导致分数不准确。我知道这是由于 UITableView 重用了单元格。
我的主 vc 中的 tableview 数据源只是来自 plist 文件的所有问题的标签。
我的自定义 tableviewcell 类的代码是
class QuestionsTableViewCell: UITableViewCell {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var selection: UISegmentedControl!
var question: String = "" {
didSet {
if (question != oldValue) {
questionLabel.text = question
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//Just for testing
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
print("value is ", sender.selectedSegmentIndex);
}
}
视图存储在 .XIB 文件中的位置。
我的主要 vc 的代码是
class ViewController: UIViewController, UITableViewDataSource {
let questionsTableIdentifier = "QuestionsTableIdentifier"
@IBOutlet var tableView:UITableView!
var questionsArray = [String]();
var questionsCellArray = [QuestionsTableViewCell]();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let path = Bundle.main.path(forResource:
"Questions", ofType: "plist")
questionsArray = NSArray(contentsOfFile: path!) as! [String]
tableView.register(QuestionsTableViewCell.self,
forCellReuseIdentifier: questionsTableIdentifier)
let xib = UINib(nibName: "QuestionsTableViewCell", bundle: nil)
tableView.register(xib,
forCellReuseIdentifier: questionsTableIdentifier)
tableView.rowHeight = 108;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questionsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: questionsTableIdentifier, for: indexPath)
as! QuestionsTableViewCell
let rowData = questionsArray[indexPath.row]
cell.question = rowData
return cell
}
@IBAction func calculate(_ sender: UIButton) {
var score = 0
for cell in tableView.visibleCells as! [QuestionsTableViewCell] {
score += cell.selection.selectedSegmentIndex
}
let msg = "Score is, \(score)"
print(msg)
}
@IBAction func reset(_ sender: UIButton) {
for cell in tableView.visibleCells as! [QuestionsTableViewCell] {
cell.selection.selectedSegmentIndex = 0;
}
}
}
我想做的只是跟踪数组中问题单元格的所有“选择”更改,然后在 cellForRowAt 中使用该数组。我只是对如何动态跟踪另一个类中的视图的更改感到困惑。我是 Swift 的新手,想解决这个问题,这是一种合适的 MVC 方式。谢谢
【问题讨论】:
-
TableView 单元格被重用为滚动以使其平滑,因此您无法在其中存储信息。您需要在后台将分段控件的状态存储在数据模型中,然后根据数据在
cellForRow方法中设置它的状态。 -
@Chris“让它顺利”这不是原因。实际上,单元格重用是平滑滚动的问题。
-
@matt 是为了响应吗?还是只是为了减少内存开销?
-
用于内存开销。
-
这很有道理 - 谢谢你们! :) 我知道重用对我的代码意味着什么,但现在我知道为什么要使用它了。
标签: ios swift uitableview model-view-controller