我正在尝试创建一个表视图,该表视图使用接收来自用户输入的textFields显示在另一个视图控制器中生成的数据,然后使用Core Data保存这些输入,然后将它们加载到tableView单元格中,除非它们不完全不会加载到单元格上。
我真的很困,我不知道该怎么尝试
这是第一个包含tableView的VC
import UIKit
import CoreData
let appDelegate = UIApplication.shared.delegate as? AppDelegate
class FriendsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var friends : [Friend] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
if friends.count >= 1{
let endIndex = IndexPath(row: friends.count - 1, section: 0)
tableView.scrollToRow(at: endIndex, at: .bottom, animated: false)
}
}
@IBAction func addFriendsButtonWasPressed(_ sender: Any) {
performSegue(withIdentifier: "toCreateFriends", sender: self)
}
func fetchCoreDataObjects(){
self.fetch { (complete) in
if complete{
if friends.count >= 1 {
tableView.isHidden = false
}else {
tableView.isHidden = true
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FC") as? FriendCell else{
return UITableViewCell()
}
let friend = friends[indexPath.row]
cell.configureCell(friend: friend)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction , indexPath) in
self.removeFriend(atIndexPat: indexPath)
self.fetchCoreDataObjects()
tableView.deleteRows(at: [indexPath], with: .automatic)
}
deleteAction.backgroundColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
return [deleteAction]
}
}
extension FriendsVC {
func fetch(completion : (_ complete : Bool)->()){
guard let managedContext = appDelegate?.persistentContainer.viewContext else{return}
let fetchRequest = NSFetchRequest<Friend>(entityName: "Friend")
do{
friends = try managedContext.fetch(fetchRequest)
completion(true)
} catch{
debugPrint("Couldn't fetch\(error.localizedDescription)")
completion(false)
}
}
func removeFriend(atIndexPat indexPath: IndexPath){
guard let managedContext = appDelegate?.persistentContainer.viewContext else {return}
managedContext.delete(friends[indexPath.row])
do {
try managedContext.save()
} catch{
debugPrint("Couldn't remove\(error.localizedDescription)")
}
}
}
-------------------------------------------------- -------------------------这是用户应在其中创建新朋友数据的另一个VC
import UIKit
import CoreData
class CreateFriendsVC: UIViewController, UITableViewDelegate {
@IBOutlet weak var nameLbl: UITextField!
@IBOutlet weak var ageLbl: UITextField!
@IBOutlet weak var genderLbl: UITextField!
@IBOutlet weak var createBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
createBtn.bindToKeyboard()
let tap = UITapGestureRecognizer(target: self, action: #selector(CreateFriendsVC.handleTap))
let pan = UIPanGestureRecognizer(target: self, action: #selector(CreateFriendsVC.handleTap))
view.addGestureRecognizer(tap)
view.addGestureRecognizer(pan)
}
@objc func handleTap(){
view.endEditing(true)
}
@IBAction func createBtnPressed(_ sender: Any) {
if nameLbl.text != "" && ageLbl.text != "" && genderLbl.text != "" {
self.save { (complete) in
if complete{
dismiss(animated: true, completion: nil)
}
}
}
dismiss(animated: true, completion: nil)
}
func save(completion : (_ finished : Bool)->()){
guard let managedContext = appDelegate?.persistentContainer.viewContext else{return}
let friend = Friend(context: managedContext)
friend.age = ageLbl.text!
friend.gender = genderLbl.text!
friend.name = nameLbl.text!
do{
try managedContext.save()
completion(true)
print("Save success")
print(friend.age!)
} catch{
debugPrint("Couldn't Save: \(error.localizedDescription)")
completion(false)
}
}
}
================================================ =========================这是自定义单元格生成器
import UIKit
class FriendCell: UITableViewCell {
@IBOutlet weak var nameTxtLbl: UILabel!
@IBOutlet weak var ageTxtLbl: UILabel!
@IBOutlet weak var genderTxtLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(friend : Friend){
self.nameTxtLbl.text = friend.name
self.ageTxtLbl.text = friend.age
self.genderTxtLbl.text = friend.gender
}
}
预期结果应该是一个表格视图,其中包含显示所有用户输入数据的单元格。 实际结果是一个空的表格视图单元格
答案 0 :(得分:0)
在重新加载之前,您需要在fetchCoreDataObjects()
中执行viewWillAppear
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchCoreDataObjects()
self.tableView.reloadData()
if friends.count >= 1{
let endIndex = IndexPath(row: friends.count - 1, section: 0)
tableView.scrollToRow(at: endIndex, at: .bottom, animated: false)
}
}
答案 1 :(得分:0)
您永远不会调用fetchCoreDataObjects()。在ViewDidLoad()或ViewWillApear()中调用此函数。
并更改如下代码。
var friends : [Friend] = [] {
didSet {
self.tableView.reloadData()
if friends.count >= 1{
let endIndex = IndexPath(row: friends.count - 1, section: 0)
tableView.scrollToRow(at: endIndex, at: .bottom, animated: false)
}
}
}