将值从细节发送回主数据

时间:2015-10-04 04:27:45

标签: ios swift segue master-detail

我在Swift中使用了master-detail模型。 但是,我想将详细视图中创建的类对象发送回主视图。我在主视图中编写了一个展开函数,但是我无法在详细视图中看到后退按钮,因此我无法按住Ctrl键将其拖动到退出处。

有谁知道如何设置后退按钮以使其可见?

1 个答案:

答案 0 :(得分:1)

您可以在用户更新详细视图控制器中的字段时直接更新模型,而不必担心将某些内容连接到后退按钮。为此,您可以将引用传递给包含要更新的属性的某个模型对象(确保它是引用类型,例如class,而不是struct

例如:

class Person {
    var firstName: String?
    var lastName: String?
}

class MasterViewController: UIViewController {

    @IBOutlet weak var firstNameLabel: UILabel!
    @IBOutlet weak var lastNameLabel: UILabel!

    var person = Person()

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let destination = segue.destinationViewController as? DetailViewController {
            destination.person = person
        }
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        firstNameLabel.text = person.firstName
        lastNameLabel.text = person.lastName
    }
}

class DetailViewController: UIViewController,UITextFieldDelegate {

    var person: Person?

    @IBOutlet weak var firstNameTextField: UITextField!
    @IBOutlet weak var lastNameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        firstNameTextField.text = person?.firstName
        lastNameTextField.text = person?.lastName
    }

    // Note, I specified the detail view controller to be the delegate
    // for the two text fields in IB: I then can detect when editing is
    // done and act accordingly.

    func textFieldDidEndEditing(textField: UITextField) {
        switch textField {
        case firstNameTextField:
            person?.firstName = textField.text
        case lastNameTextField:
            person?.lastName = textField.text
        default:
            assert(false, "unidentified textField \(textField)")
        }
    }
}

您可以在viewDidAppear中使用主视图控制器更新,就像我上面所做的那样,或者更好的是,您可以为模型属性添加观察者。但希望它说明了基本的想法。