I have a ViewController with tableview and a separate nib for create the table view cell,the cell contains a textview. press the add button,then the tableview will create a new cell,so i can input text into the textView. i want to insert cells to first row each time ,no matter how many cells existed. Finally ,press the done button to save the text to coredata.
the xib Entities name is "Checklist",the xib file name is "ChecklistCell"
class ChecklistViewController:
class ChecklistViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var items = [Checklist]()
var cellTextView:ChecklistCell!
@IBOutlet weak var tableView: UITableView!
@IBOutlet var toolBar: UIToolbar!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
struct TableViewCellIdentifiers{
static let checklistCell = "ChecklistCell"
}
@IBAction func addItem(){
//i don't know how to write this code
}
@IBAction func toolBarDoneButton(_ sender: UIBarButtonItem) {
//write data to coredata
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let item = Checklist(context: context)
item.textView = cellTextView.textView.text
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "ChecklistCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "ChecklistCell")
}
override func viewWillAppear(_ animated: Bool) {
getData()
tableView.reloadData()
}
func getData(){
do {
items = try context.fetch(Checklist.fetchRequest())
} catch {
print("Fetching Failed")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifiers.checklistCell, for: indexPath) as! ChecklistCell
let item = items[indexPath.row]
if let myItem = item.textView {
cell.textView.text = myItem
}
cell.textView.inputAccessoryView = toolBar
return cell
}
}