我做了一个小测验,其中 tableView 包含不同的问题和答案作为标签和文本字段。
如果输入正确答案,tableView 单元格变为绿色,textField Text 已设置,并且 textfield 变为不可编辑。
我的问题是这些设置都没有保存。我需要它记住问题是否被正确回答并相应地更改单元格。我知道我可以使用核心数据或用户默认值来保存内容,但我不确定如何获取正确回答的特定单元格以保存。
我的代码如下:
表视图控制器
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
let questions = ["what is 3 + 5", "what is the meaning of life","what
is the number from the jim carrey movie"]
let answers = ["8","42","23"]
var textfieldColor = UIColor(red:0.98, green:0.23, blue:0.42,
alpha:1.0)
var textFieldText = ""
var isTextFieldEditable = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return answers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Answers", for: indexPath) as! TableViewCell
cell.question.text = questions[indexPath.row]
cell.backgroundColor = textfieldColor
cell.answerOutlet.text = textFieldText
cell.isUserInteractionEnabled = isTextFieldEditable
cell.answerOutlet.delegate = self
return cell
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
print(answers.contains(textField.text!))
if answers.contains(textField.text!)
{
textfieldColor = UIColor.green
textFieldText = textField.text!
isTextFieldEditable = false
let rowNumber = answers.index(of: textField.text!)
let indexPath = IndexPath(item: rowNumber!, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)
}
return true
}
}
表视图单元:
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var question: UILabel!
@IBAction func Answer(_ sender: UITextField)
{
}
@IBOutlet weak var answerOutlet: UITextField!
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
}
}
谢谢您的帮助。