Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/94.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-can';t添加按钮操作后从TableView重新加载数据_Ios_Swift_Tableview_Alert_Reloaddata - Fatal编程技术网

Ios Swift-can';t添加按钮操作后从TableView重新加载数据

Ios Swift-can';t添加按钮操作后从TableView重新加载数据,ios,swift,tableview,alert,reloaddata,Ios,Swift,Tableview,Alert,Reloaddata,我是斯威夫特的新手,需要你的帮助 我创建了一个带有自定义单元格的TableViewController。 我还在导航栏中创建了一个“添加”按钮,为我的tableview添加一个新值。 将显示在核心数据中保存值并在视图中获取它们 当按下add按钮时,一个UIAlertController显示出来,这是我根据需要定制的。我添加了一个取消操作和一个确定操作,但当我从警报中按下确定按钮时,新值不会显示在我的tableview中。我必须切换到tableview显示的其他viewcontroller 我在代

我是斯威夫特的新手,需要你的帮助

我创建了一个带有自定义单元格的TableViewController。 我还在导航栏中创建了一个“添加”按钮,为我的tableview添加一个新值。 将显示在核心数据中保存值并在视图中获取它们

当按下add按钮时,一个UIAlertController显示出来,这是我根据需要定制的。我添加了一个取消操作和一个确定操作,但当我从警报中按下确定按钮时,新值不会显示在我的tableview中。我必须切换到tableview显示的其他viewcontroller

我在代码中的不同点上添加了
groupsTableView.reloadData()
,但无法使其正常工作

希望有人能帮助我

来自MasterViewController的代码:

import UIKit
import CoreData

class MasterViewController: UITableViewController {

    var groups: [Groups] = []

    @IBOutlet weak var groupsTableView: UITableView!

    var groupsTextField: UITextField?


    override func viewDidLoad() {
        super.viewDidLoad()

        groupsTableView.delegate = self
        groupsTableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    override func viewWillAppear(_ animated: Bool) {

        // Core date initialization
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }

        let managedContext = appDelegate.persistentContainer.viewContext

        let fetchRequest: NSFetchRequest<Groups> = Groups.fetchRequest()

        do {
            groups = try managedContext.fetch(fetchRequest)

            groupsTableView.reloadData()

        } catch {
            // TODO: error handling
            print("Could not fetch groups")
        }

        navigationItem.leftBarButtonItem = editButtonItem

        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject))
        navigationItem.rightBarButtonItem = addButton
    }


    // MARK: - add new Group

    @objc func insertNewObject() {
        let addButtonAlert = UIAlertController(title: "Neue Gruppe", message: "Füge eine neue Gruppe deiner Liste hinzu", preferredStyle: .alert)
        addButtonAlert.addTextField { (UITextField) in
            self.groupsTextField = UITextField
            self.groupsTextField?.placeholder = "Name der Gruppe"
            self.groupsTextField?.clearButtonMode = .whileEditing
        }
        let okAction = UIAlertAction(title: "Hinzufügen", style: .default, handler: addNewGroup)
        let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil)

        addButtonAlert.addAction(okAction)
        addButtonAlert.addAction(cancelAction)

        self.present(addButtonAlert, animated: true, completion: nil)

    }

    func addNewGroup(_:UIAlertAction) -> Void {
        let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")

        do {
            try group?.managedObjectContext?.save()

            groupsTableView.reloadData()

        } catch {
            // TODO: error handling
            print("Could not save group")
        }
    }

    // MARK: - Segue

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        guard let destination = segue.destination as? DetailViewController,
            let selectedRow = self.groupsTableView.indexPathForSelectedRow?.row else {
                return
        }
        destination.group = groups[selectedRow]
        destination.title = groups[selectedRow].groupTitle
    }

    // MARK: - delete Group

    func deleteGroup(at indexPath: IndexPath) {
        let group = groups[indexPath.row]

            guard let managedContext = group.managedObjectContext else {
                return
        }

        managedContext.delete(group)

        do {
            try managedContext.save()

            groups.remove(at: indexPath.row)

            groupsTableView.deleteRows(at: [indexPath], with: .automatic)
        } catch {
            //TODO: error handling
            print("Could not delete Group")

            groupsTableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }

    // MARK: - Table View

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groups.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = groupsTableView.dequeueReusableCell(withIdentifier: "GroupsTableViewCell", for: indexPath)  as! GroupsTableViewCell
        let object = groups[indexPath.row]

        cell.groupTitleLabel?.text = object.groupTitle

        return cell
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            deleteGroup(at: indexPath)
        }
    }
}
导入UIKit
导入CoreData
类MasterViewController:UITableViewController{
变量组:[组]=[]
@IBVAR组稳定视图:UITableView!
var groupsTextField:UITextField?
重写func viewDidLoad(){
super.viewDidLoad()
groupsTableView.delegate=self
groupsTableView.dataSource=self
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
}
覆盖函数视图将出现(uo动画:Bool){
//核心日期初始化
让appDelegate=UIApplication.shared.delegate作为?appDelegate else{
返回
}
让managedContext=appDelegate.persistentContainer.viewContext
let fetchRequest:NSFetchRequest=Groups.fetchRequest()
做{
groups=尝试managedContext.fetch(fetchRequest)
groupsTableView.reloadData()
}抓住{
//TODO:错误处理
打印(“无法获取组”)
}
navigationItem.leftBarButtonItem=editButtonItem
让addButton=UIBarButtonItem(barButtonSystemItem:.add,目标:self,操作:#选择器(insertNewObject))
navigationItem.rightBarButtonItem=addButton
}
//标记:-添加新组
@objc func insertNewObject(){
让AddButtonnalert=UIAlertController(标题:“Neue Gruppe”,消息:“Füge eine Neue Neue Gruppe deiner Liste hinzu”,首选样式:。警报)
AddButtonAllert.addTextField{(UITextField)位于
self.groupsTextField=UITextField
self.groupsTextField?.placeholder=“Name der Gruppe”
self.groupsTextField?.clearButtonMode=.whileEdit
}
让okAction=UIAlertAction(标题:“Hinzufügen”,样式:。默认,处理程序:addNewGroup)
让cancelAction=UIAlertAction(标题:“Abbrechen”,样式:。取消,处理程序:nil)
addButtonAllert.addAction(okAction)
addButtonAllert.addAction(取消操作)
self.present(addButtonAlert,动画:true,完成:nil)
}
func addNewGroup(uquo:UIAlertAction)->Void{
let group=Groups(groupId:UUID(),groupTitle:groupsTextField!.text??)
做{
尝试组?.managedObjectContext?.save()
groupsTableView.reloadData()
}抓住{
//TODO:错误处理
打印(“无法保存组”)
}
}
//马克:塞格
覆盖功能准备(对于segue:UIStoryboardSegue,发送方:有吗?){
guard let destination=segue.destination as?DetailViewController,
让selectedRow=self.groupsTableView.indexPathForSelectedRow?.row else{
返回
}
destination.group=组[selectedRow]
destination.title=组[selectedRow].groupTitle
}
//标记:-删除组
func deleteGroup(在indexath:indexath处){
let group=groups[indexPath.row]
guard let managedContext=group.managedObjectContext-else{
返回
}
managedContext.delete(组)
做{
请尝试managedContext.save()
groups.remove(位于:indexPath.row)
groupsTableView.deleteRows(位于:[indexPath],带:。自动)
}抓住{
//TODO:错误处理
打印(“无法删除组”)
groupsTableView.reloadRows(位于:[indexPath],带:。自动)
}
}
//标记:-表视图
重写func numberOfSections(在tableView:UITableView中)->Int{
返回1
}
重写func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回组数
}
重写func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
将cell=groupsTableView.dequeueReusableCell(标识符为:“GroupsTableViewCell”,for:indexath)设为!GroupsTableViewCell
让对象=组[indexPath.row]
cell.groupTitleLabel?.text=object.groupTitle
返回单元
}
重写func tableView(tableView:UITableView,canEditRowAt indexath:indexPath)->Bool{
//如果不希望指定的项可编辑,则返回false。
返回真值
}
重写func tableView(tableView:UITableView,commit editingStyle:UITableViewCell.editingStyle,forRowAt indepath:indepath){
如果editingStyle==.delete{
deleteGroup(位于:indexPath)
}
}
}

将组项添加到您的组数组中,然后重新加载您的表视图,如下所示:-

func addNewGroup(_:UIAlertAction) -> Void {
    let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")
    do {
        try group?.managedObjectContext?.save()
        self.groups.append(group)
        groupsTableView.reloadData()
    } catch {
        // TODO: error handling
        print("Could not save group")
    }
}

在哪里将新插入的组添加到组中?我想在addNewGroup函数中创建一个新的NSManagedObject,并将其保存在核心数据中。数组组是所有保存的组对象的数组。当我切换ViewController并向后导航时,tableview会显示新保存的组,因为视图中会出现重新加载的数据,但当AddButtonAllert被取消时不会出现。我尝试了一些方法,并在
addNewGroup
函数中编写了一条if-let语句,现在tableview会按其应该的方式加载值!但这是正确的处理方式吗<代码>