将变量分配给传入视图控制器的正确方法

时间:2019-01-29 14:03:27

标签: ios swift

我正在开发一个简单的主从应用程序,该应用程序使用许多表格作为模态。

详细信息ViewController是一个TableViewController,每个单元格中都有编辑按钮。

我想找到一种方法,当单击编辑按钮时,将单元格的对象分配给传入的表单,以便可以向表单显示正确的数据,但是我不确定是否已经完成这是正确的方法...

我对编辑按钮使用了@IBAction,如下所示:

    // DetailViewController.swift

    var activeBooking: Booking? = nil


    @IBAction func onEditBooking(_ sender: Any) {
        let button = sender as! UIButton
        let cell = button.superview!.superview as! BookingCell
        self.activeBooking = cell.booking!
    }

,然后在我的prepare(for segue:)方法中,我有以下内容:

    // DetailViewController.swift

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier === "editBookingSegue" {
            let controller = segue.destination as! EditRoomViewController
            controller.booking = activeBooking
        }
    }

问题1 这个可以吗?我知道通过segues传递数据是合法的,并且可以正常工作,但是我担心这两种方法的执行顺序,是否存在竞争条件,在这种情况下,segue prepare方法可以在{{ 1}}作业正在进行中?

问题2 另外,我不喜欢使用activeBooking-看起来很杂乱。有没有更简单的方法可以遍历按下的按钮到button.superview!.superview?我想另一个选择是,在这种情况下,我可以通过对TableViewCell进行子类化来简化它,这样UIButton对象也可以直接存储在按钮上。

1 个答案:

答案 0 :(得分:0)

让单元格完全拥有按钮,并使用委托方法将操作传递给视图控制器。您的视图控制器不需要了解该按钮。让按钮在其单元格上调用方法。然后该单元向其代表报告预订请求。

//myCell.swift

@IBAction func onEditBooking(_ sender: Any) {
    bookingDelegate.edit(booking: self.booking)
}

// DetailViewController.swift

func edit(booking: Booking) {
    activeBooking = booking
    performSegue(withIdentifier: "editBookingSegue", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "editBookingSegue" {
         let controller = segue.destination as! EditRoomViewController
         controller.booking = activeBooking
}

或者更好的方法是在“准备序列”方法中使用发件人值来确定按下了哪个按钮。给它分配标签或其他内容。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "editBookingSegue" {
         let button = sender as! UIButton
         let booking = bookingsArray[button.tag]
         let controller = segue.destination as! EditRoomViewController
         controller.booking = booking
}