【发布时间】:2020-06-29 17:09:07
【问题描述】:
我正在尝试编写一个记事卡应用程序,该应用程序允许用户在创建每个记事卡时输入术语和定义(我正在使用 Swift 进行编码)。我创建了一个记事卡的表格视图,用户可以在其中输入每个记事卡的术语和定义。我正在通过 Realm 保存他们的数据。 目前,我可以保存他们添加的记事卡数量。但是,我无法弄清楚如何保存他们对每张笔记卡的术语和定义的输入(我要求用户通过术语的文本字段和定义的文本字段进行输入)。 因为我必须为 UITableViewCell 创建另一个类(以避免插座无法连接到重复内容错误),所以我无法访问 CreateNewSetTableViewController 中的 termTextField 和 defTextField,因此无法保存或对用户数据执行任何操作。 任何帮助将不胜感激,我已经尝试解决这个问题大约 2 天了。非常感谢:)
import UIKit
import RealmSwift
class NotecardTableViewCell: UITableViewCell {
@IBOutlet weak var termTextField: UITextField!
@IBOutlet weak var defTextField: UITextField!
}
class CreateNewSetTableViewController: UITableViewController {
var noteCards: Results<Notecard>?
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
loadNotecards() //load up all the categories currently owned
}
//MARK: - Navigation Bar Methods
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
let newItem = Notecard()
newItem.term = "wooho"
newItem.def = "asdf"
self.save(notecard: newItem)
tableView.reloadData()
}
@IBAction func doneButtonPressed(_ sender: UIBarButtonItem) {
_ = navigationController?.popToRootViewController(animated: true)
}
//MARK: - Data Manipulation Methods
func save(notecard: Notecard){
do {
try realm.write{
realm.add(notecard)
}
}
catch{
print (error)
}
tableView.reloadData()
}
func loadNotecards(){
noteCards = realm.objects(Notecard.self)
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return noteCards?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NotecardCell", for: indexPath) as! NotecardTableViewCell
return cell
}
}
【问题讨论】:
标签: ios swift xcode uitableview realm