故事板:使用委托/协议方法解除Popover

时间:2012-06-10 06:00:22

标签: xcode uibutton storyboard popover

我已经阅读了的内容,虽然大多数似乎是关于非故事板的方法,但我认为我拼凑了一些并弄明白了。但是,以下代码不会导致我的popover被解雇。 Popover中的dismissPopoverButtonPressed按钮执行但委托中的dismissPopover方法中的断点永远不会发生。非常感谢有人密切关注代码以发现错误。

由于

在下文中,NewGameViewController包含一个UIButton。按此按钮会弹出Popover Segue并显示包含PopViewController UIView的弹出框。

NewGameViewController.h

#import "PopViewController.h"
@interface NewGameViewController: UIViewController <DismissPopoverDelegate>
{
    UIPopoverController *popover;
}

NewGameViewController.m

@implementation NewGameViewController
-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"popoverSegue"])
    {
        popover = [(UIStoryboardPopoverSegue *)segue popoverController];
        // getting warning: Assigning to 'id<UIPopoverControllerDelegate>' from incompatible type 'NewGameViewController *const__strong'
        //popover.delegate = self;
    }
}

-(void)dismissPopover
{
    [popover dismissPopoverAnimated:YES];
}

PopViewController.h

@protocol DismissPopoverDelegate <NSObject>
-(void) dismissPopover;
@end

@interface PopViewController: UIViewController
{
    __unsafe_unretained id<DismissPopoverDelegate> delegate;
}

@property (nonatomic, assign) id<DismissPopoverDelegate> delegate;
-(IBAction)dismissPopoverButtonPressed:(id)sender;
@end

PopViewController.m

#import "NewGameViewController.h"
@implementation PopViewController
@synthesize delegate;
-(IBAction)dismissPopoverButtonPressed:(id)sender
{
    [self.delegate dismissPopover];
}

1 个答案:

答案 0 :(得分:13)

当从故事板segue链接到弹出控制器时,segue的popoverController属性指的是标准的UIPopoverController。此控制器本身具有一个属性contentViewController,它将表示实际在弹出框中显示的视图控制器,在您的情况下为PopViewController

因此,当你真正需要将自己设置为popover的 content 视图控制器的委托时,你当前的代码将自己设置为popover控制器的委托。

您仍然需要保留对弹出控制器的引用,以解除,以便保留现有代码,但进行以下更改:

-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"popoverSegue"])
    {
        popover = [(UIStoryboardPopoverSegue *)segue popoverController];
        // Get a reference to the content view controller of the popover
        PopViewController *popVC = (PopViewController*)popover.contentViewController;
        // Set ourselves as the content VC's delegate
        popVC.delegate = self;
    }
}