iphone - 告诉哪个 ViewController 推送了 DetailViewController

标签 iphone objective-c ios

我有一个 DetailViewController,当选择 Cell 时,它是通过 Storyboard segues 从 RootViewController1 或 RootViewController2 推送/输入的。

DetailViewController 有一个带有 IBAction 的按钮。我可以像这样编程 Action 吗:

如果父 ViewController 是 RootViewController2,则返回。否则,执行操作。 像这样:

-(IBAction)actionButtonPressed:(id)sender
{
    if (parentViewController == RootViewController2) {
        return;
    }

    //Else this is done:
    textLabel.text = @"Test";
}

但我不确定如何让它发挥作用,如果有这样的例子就好了。如果您需要更多信息,请告诉我!

编辑:

代码现在看起来像这样:

#import "RootViewController2.h"

...

-(IBAction)actionButtonPressed:(id)sender
{
    if([self.parentViewController isKindOfClass:[RootViewController2 class]]) {
        return;
    }

    //Else this is done:
    textLabel.text = @"Test";
}

但是 Action 仍然从两个 View 执行。进一步的建议?

最佳答案

正如@Matt 提到的, View Controller 存储在一个数组中。您可以像这样访问导航 Controller 数组:

[self.navigationController.viewControllers lastobject ]
[self.navigationController.viewControllers objectAtIndex:2];

You can also get a reference to the parent view controller like this:
self.parentViewController
self.presentingViewController

无论您如何获得对父级的引用,您仍然需要有一种方法来比较该引用。你可以像这样使用内省(introspection) if ([object isKindOfClass:MyClass class])。但是不知何故,在这种方法中(使用 View Controller 数组)你需要一个对每个父对象的对象引用。这是一个棘手的方法。

另一种可能更简单的方法是在 View Controller 中设置一个属性值,然后在 -(void)prepareForSegue .... block 中继续它。像这样:

 MyClass *myClass = segue.destinationViewController;
 myClass.myLogicProperty = @"mommy";

并且在另一个 View Controller 的另一个 segue 中

MyClass *myClass = segue.destinationViewController;
 myClass.myLogicProperty = @"daddy";

现在,当您按下按钮时,您可以只针对这些值,然后做正确的事情。

if ([self.myLogicProperty isEqualTo:@"daddy"]) {
   //take action
}
else if ([self.myLogicProperty isEqualTo:@"mommy"]) {
   //take action
}
else {
//do something if no match
}

不知道您的具体需求,我会推荐后者并建议不要尝试使用 viewcontrollers 数组。

希望对您有所帮助。

关于iphone - 告诉哪个 ViewController 推送了 DetailViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926142/

相关文章:

iphone - 无法在 UIView 中制作流畅的动画

iphone - 从地址簿中获取 iPhone 电话号码标签

ios - firebase objective c 查询

objective-c - iPad/iPhone 方向问题

ios - 找不到 Metal iOS 的资源

ios - UITableViewCell - 如何处理来自 Nibs 的动态大小的内容 View

ios - 需要检查 UITextField 是否包含两个(并且只有两个)iOS 中每个最少 2 个字符的字符串

ios - 搜索结果 TableView 未被选中

ios - 如何从照片库等设备库中挑选/浏览音频文件?

ios - 如何从 native ios 应用程序直播到 YouTube 帐户