从IBAction函数中搜索/推送到其他视图控制器?

时间:2018-12-28 08:48:22

标签: swift push viewcontroller ibaction sigabrt

我试图以编程方式推送到下一个视图控制器,这样我就可以将数据保存在核心数据中,然后推送到下一个视图控制器。基本上,当我点击带有IBAction的按钮时,它将完成所有这一切。但是,每当我在IBAction函数中使用此代码时,都会收到线程1 SIGABRT错误:

    @IBAction func onPlusTapped(){

        let alert = UIAlertController(title: "New Course", message: nil, preferredStyle: .alert)

        alert.addTextField { (textField) in
            textField.placeholder = "Course"
        }
        let action = UIAlertAction(title: "New", style: .default){ (_) in
            let course = alert.textFields!.first?.text!
            print(course)

            let coursy = Course(context: PersistenceService.context)
            coursy.name = course
            PersistenceService.saveContext()
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)

        // jump to next view controller
        segway()

    }

    func segway(){
    let storyBoard: UIStoryboard = UIStoryboard(name: "viewcontroller", bundle: nil)
    let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "viewcontroller") as! ViewController
    self.present(balanceViewController, animated: true, completion: nil)
    }

}

2 个答案:

答案 0 :(得分:0)

如果Course保存后想跳到下一个viewController,则必须在func segway()完成块中调用UIAlertAction

示例:

let action = UIAlertAction(title: "New", style: .default){ (_) in
            let course = alert.textFields!.first?.text!
            print(course)

            let coursy = Course(context: PersistenceService.context)
            coursy.name = course
            PersistenceService.saveContext()
            // jump to next view controller
            segway()

        }

还要仔细检查您的故事板名称,balanceViewController的标识符为“ viewcontroller”。

答案 1 :(得分:0)

为什么要同时跳过segway()并发出警报?您不应该将segway()放在警报动作中吗?

请参见以下代码。

@IBAction func onPlusTapped() {

        let alert = UIAlertController(title: "New Course", message: nil, preferredStyle: .alert)

        alert.addTextField { (textField) in
            textField.placeholder = "Course"
        }
        let action = UIAlertAction(title: "New", style: .default){ (_) in
            let course = alert.textFields!.first?.text!
            print(course)

            let coursy = Course(context: PersistenceService.context)
            coursy.name = course
            PersistenceService.saveContext()

             // jump to next view controller
            segway()
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }


    func segway() {
        let storyBoard: UIStoryboard = UIStoryboard(name: "viewcontroller", bundle: nil)
        let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "viewcontroller") as! ViewController
        self.present(balanceViewController, animated: true, completion: nil)
    }
}

希望获得帮助!