【问题标题】:Send a Delegate message from UIPopover to Main UIViewController从 UIPopover 向主 UIViewController 发送代表消息
【发布时间】:2012-01-16 18:25:02
【问题描述】:

我试图在我的UIPopover 中使用一个按钮在我的主要UIViewController 中创建一个UITextView,我的代码看起来像这样(PopoverView.h 文件):

@protocol PopoverDelegate <NSObject> 

- (void)buttonAPressed;

@end

@interface PopoverView : UIViewController <UITextViewDelegate> {  //<UITextViewDelegate>

    id <PopoverDelegate> delegate;
    BOOL sendDelegateMessages;
}
@property (nonatomic, retain) id delegate;
@property (nonatomic) BOOL sendDelegateMessages;
@end

然后在我的PopoverView.m 文件中:

- (void)viewDidLoad
{
    [super viewDidLoad];

UIButton * addTB1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
addTB1.frame = CGRectMake(0, 0, 100, 50);
[addTB1 setTitle:@"Textbox One" forState:UIControlStateNormal];
[self.view addSubview:addTB1];    // Do any additional setup after loading the view from its nib.
[addTB1 addTarget:self action:@selector(buttonAPressed) 
forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonAPressed
{
    NSLog(@"tapped button one");

    if (sendDelegateMessages)
        [delegate buttonAPressed];
}

还有我的MainViewController.m

- (void)buttonAPressed {

    NSLog(@"Button Pressed");
    UITextView *textfield = [[UITextView alloc] init];
    textfield.frame = CGRectMake(50, 30, 100, 100);
    textfield.backgroundColor = [UIColor blueColor];
    [self.view addSubview:textfield];
}

我正在使用委托协议来链接 popover 和 ViewController,但我一直坚持如何让我的 BOOL 语句链接 PopoverView 和 MainViewController 中的 -(void)buttonAPressed,这样当我按下按钮时弹出一个文本视图出现在主 VC 中。我该怎么做呢?

【问题讨论】:

    标签: ios uiviewcontroller delegates uitextview uipopovercontroller


    【解决方案1】:

    在您创建PopoverViewMainViewController 中,请务必设置其delegate 属性,否则在PopoverView 中向delegate 发送消息将无济于事。

    例如在MainViewController.m:

    PopoverView *pov = [[PopoverView alloc] initWithNibName:nil bundle:nil];
    pov.delegate = self;  // <-- must set this
    thePopoverController = [[UIPopoverController alloc] initWithContent...
    

    我不确定您为什么需要 sendDelegateMessages 变量。即使使用该布尔值,您也必须设置 delegate 属性,以便 PopoverView 具有将消息发送到的实际对象引用。

    如果您想确保delegate 对象已经实现了您将要调用的方法,您可以这样做:

    if ([delegate respondsToSelector:@selector(buttonAPressed)])
        [delegate buttonAPressed];
    


    此外,delegate 属性应使用assign(或weak,如果使用ARC)而不是retain 声明(请参阅Why use weak pointer for delegation? 以获得解释):

    @property (nonatomic, assign) id<PopoverDelegate> delegate;
    


    另一件事是如果你不使用ARC,你需要在MainViewController中的buttonAPressed方法的末尾添加[textfield release];以避免内存泄漏。

    【讨论】:

    • 这绝对是固定的,非常感谢!并感谢您的提示。会阻止我犯更多的错误。
    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 2020-11-14
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多