使用Swift将从textField收到的用户回答保存在tableView上,可以按照以下步骤进行:
textFieldShouldReturn
,用于在用户按下Return键时保存用户回答。var answers = [String]()
。textFieldShouldReturn
方法中,将textField的文本添加到数组中,并刷新tableView,例如:func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let answer = textField.text {
answers.append(answer)
tableView.reloadData()
textField.text = ""
}
return true
}
numberOfRowsInSection
和cellForRowAt
,用于显示保存的用户回答,例如:func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return answers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnswerCell", for: indexPath)
cell.textLabel?.text = answers[indexPath.row]
return cell
}
viewDidLoad
方法中,设置tableView的代理和数据源为视图控制器,并注册tableView的cell,例如:override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "AnswerCell")
}
这样,当用户在textField中输入回答并按下Return键时,回答会被保存到数组中,并在tableView中显示出来。
TVP技术夜未眠
云+社区技术沙龙[第28期]
云+社区沙龙online [国产数据库]
腾讯云GAME-TECH游戏开发者技术沙龙
DBTalk
云+社区技术沙龙[第9期]
腾讯云GAME-TECH游戏开发者技术沙龙
T-Day
云+社区技术沙龙[第6期]
云+社区技术沙龙[第16期]
领取专属 10元无门槛券
手把手带您无忧上云