如何从警报的文本字段中获取文本并将其作为单元格的文本标签?

时间:2017-01-07 22:26:05

标签: ios swift uitableview uialertcontroller

class CoursesTableViewController: UITableViewController {
    var nameOfCourse = "";

    @IBAction func newCourse(_ sender: AnyObject) {
            //1. Create the alert controller.
            // var nameOfCourse = "";
            let alert = UIAlertController(title: "New Course", message: "Enter the course name.", preferredStyle: .alert);

            //2. Add the text field. You can configure it however you need.
            alert.addTextField(configurationHandler: { (textField) -> Void in
                textField.placeholder = ""
            })

            //3. Grab the value from the text field, and print it when the user clicks OK.
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                let textField = alert.textFields![0] as UITextField

                self.nameOfCourse = textField.text!

                print(self.nameOfCourse)
            }))

            alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            }))

            // 4. Present the alert.
            self.present(alert, animated: true, completion: nil)
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cells = tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath) as? CoursesTableViewCell

        cells?.textLabel.text = self.nameOfCourse

        return cells!
    }

1 个答案:

答案 0 :(得分:0)

在成功设置nameOfCourseprint(self.nameOfCourse)下方)后重新加载表格视图。