如何从该segue或目标视图控制器中访问执行segue的源视图?

时间:2016-08-12 09:43:59

标签: ios swift segue

我有一个继承自ContainerSegue的自定义UIStoryboardSegue。在perform()方法中,我需要访问执行当前segue的UIView。我怎样才能做到这一点?有可能吗?

  

换句话说,我需要访问perform()方法中的发件人

2 个答案:

答案 0 :(得分:3)

segue课程通常不跟踪sender,但由于您已定义了名为segue的自定义ContainerSegue课程,因此您可以添加sender属性:

class ContainerSegue: UIStoryboardSegue {
    // Add this property to hold the sender
    var sender: AnyObject?

    override func perform() {
        if let button = sender as? UIButton, title = button.currentTitle {
            print("button title is \(title)")
        }

        // Add remainder of perform code here
    }
}

然后在prepareForSegue中设置:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let containerSegue = segue as? ContainerSegue {
        containerSegue.sender = sender
    }
}

以类似的方式,如果您要访问sender中的destinationViewController,请向sender添加destinationViewController属性并在prepareForSegue中设置该属性}:

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

答案 1 :(得分:0)

let button = sender as! UIButton
let view = button.superview