【发布时间】:2020-10-05 23:13:16
【问题描述】:
我有一些问题要在UITableView 中用“是”或“不是”来回答,每个选项(是/否)都是单元格中自己的按钮。
首先,我必须处理点击事件,因为我必须在点击时更改按钮的backgroundColor,并且我必须添加点击的行来创建另一个带有答案的结构。
我的实际代码是这样的:
extension MyViewController: UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//click row
}
}
extension MyViewController: UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellAnswers", for: indexPath) as! MyTableViewCell
//iterate here? and how can i do that?
cell.actionYes = {
cell.buttonYes.backgroundColor = .blue
cell.buttonNo.backgroundColor = .darkGray
}
cell.actionNot = {
cell.buttonYes.backgroundColor = .darkGray
cell.buttonNo.backgroundColor = .blue
}
let question = questions[indexPath.row]
cell.question = question
return cell
}
}
如您所见,我有处理点击事件和更改背景颜色的功能,但如果我点击一个按钮,其余按钮也会发生变化。
还有我的 TableViewCell:
import UIKit
class MyTableViewCell: UITableViewCell{
@IBOutlet weak var question: UILabel!
@IBOutlet weak var buttonYes: UIButton!
@IBOutlet weak var buttonNo: UIButton!
var actionYes: (() -> Void)? = nil
var actionNo: (() -> Void)? = nil
@IBAction func answerYes(_ sender: Any) {
actionYes?()
}
@IBAction func answerNo(_ sender: Any) {
actionNo?()
}
var question: QuestionResponse!{
didSet{
updateUI()
}
}
func updateUI(){
question.text = question.value
}
}
我不知道如何迭代单元格以填充按钮上的正确颜色。
【问题讨论】:
-
从
didSelectRowAt方法内的选中单元格中获取单元格indexPath,然后使用tableView方法cellForRowAtIndexPath:获取对应的单元格 -
问题是,当您点击是或否按钮并滚动时,您还会看到具有相同答案的其他问题?
-
@gcharita yup .. 例如,我回答第一个问题是,当我滚动时,当我还没有选择任何答案时,其他问题被标记为是.. 我正在阅读我必须迭代在牢房里,但我不知道该怎么做
标签: swift xcode uitableview