简体   繁体   English

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

[英]How to access source view that perform segue from within that segue or destination view controller?

I have a custom ContainerSegue inherited from UIStoryboardSegue . 我有一个自UIStoryboardSegue继承的自定义ContainerSegue Within perform() method I need to access the UIView that performed current segue. perform()方法中,我需要访问执行当前segue的UIView How can I do this? 我怎样才能做到这一点? Is it possible? 可能吗?

In other words I need to access the sender within perform() method. 换句话说,我需要在perform()方法中访问发送者

A segue class doesn't typically keep track of the sender , but since you have defined a custom segue class called ContainerSegue , you can add a sender property to it: segue类通常不跟踪sender ,但是由于您定义了一个名为ContainerSegue的自定义segue类,因此可以向其添加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
    }
}

and then set that in prepareForSegue : 然后在prepareForSegue设置它:

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

In a similar manner, if you want to access the sender in the destinationViewController , add a sender property to the destinationViewController and set that in prepareForSegue : 以类似的方式,如果你要访问的senderdestinationViewController ,一个添加sender属性设置destinationViewController并设置在prepareForSegue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM