如何在Swift 3中对TextField进行控制警报

时间:2016-11-06 15:38:43

标签: ios swift if-statement uialertcontroller

我有两个UITextFields并希望将输入保存在核心数据中。如果TextField为空,则应该有一个类似“请插入值”的警告。

我尝试这样做:

@IBAction func buttonSave(_ sender: AnyObject) {

    let db:DB = NSEntityDescription.insertNewObject(forEntityName: "DB", into: DatabaseController.persistentContainer.viewContext) as! DB

    if timeFextField.text == "" {


        let dateAlert = UIAlertController(title: "Missung Value", message: "Please insert a date.", preferredStyle: UIAlertControllerStyle.alert)

        let okAction = UIAlertAction(title: "OK", style: .default){(action: UIAlertAction) in print("OK")
        }

        dateAlert.addAction(okAction)

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

    } else {
        if labelTypNumber.text == "" {
            let typeAlert = UIAlertController(title: "Missung Value", message: "Please select a type.", preferredStyle: UIAlertControllerStyle.alert)

            let okAction = UIAlertAction(title: "OK", style: .default){(action: UIAlertAction) in print("OK")
            }

            typeAlert.addAction(okAction)

            self.present(typeAlert, animated: true, completion: nil)
        }
        else {

            db.time = NSDate()
            db.date = timeFextField.text!
            db.typ = Double(labelTypNumber.text!)!
            db.color = colorTextField.text!
            db.notes = notesTextField.text!
            db.weather = wetterTextField.text!

            if mediSegment.selectedSegmentIndex == 0 {
                db.medi = mediTextField.text!
            } else {
                db.medi = "0"
            }

            if mediSegment.selectedSegmentIndex == 1 {
                db.medi2 = mediTextField.text!
            } else {
                db.medi2 = "0"
            }

            DatabaseController.saveContext()

            navigationController!.popViewController(animated: true)

        }
    }


}

现在当UITextField为空时,我得到一个UIAlert,但是当我从Cora Data加载数据时,应用程序崩溃了。

“致命错误:在展开Optional值时意外发现nil (lldb)“

看起来,即使显示警报,这些值也会存储在Core Data中。 有人有想法解决这个问题吗?

谢谢,许多问候。

0 个答案:

没有答案