首页 文章

如何以编程方式创建的uibutton以编程方式显示弹出窗口(不使用接口构建器)

提问于
浏览
15

我有一个我在视图控制器中以编程方式创建的按钮 . 按下按钮后,我希望它使用一种方法以编程方式创建弹出框 .

在我的视图controller.m中的ViewDidLoad中创建的按钮

UIView *moreFundInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 540, 620)];
[self.view addSubview:moreFundInfoView];
[moreFundInfoView setBackgroundColor:[UIColor RMBColor:@"b"]];

btnContact = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];


[btnContact setFrame:CGRectMake(390, 575, contactButton.width, contactButton.height)];
 btnContact.hidden = NO;
[btnContact setTitle:@"Contact" forState:(UIControlStateNormal)];
[moreFundInfoView addSubview:btnContact];

[btnContact addTarget:self action:@selector(showContactDetails:) forControlEvents:UIControlEventTouchUpInside];

然后我按下按钮时使用的方法 .

-(void) showContactDetails: (id) sender
{
UIViewController *popoverContent = [[UIViewController alloc]init];

UIView *popoverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 300)];

[popoverView setBackgroundColor:[UIColor RMBColor:@"b"]];

popoverContent.view = popoverView;

popoverContent.contentSizeForViewInPopover = CGSizeMake(200, 300);

UIPopoverController *contactPopover =[[UIPopoverController alloc] initWithContentViewController:popoverContent];

[contactPopover presentPopoverFromRect:btnContact.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES ];

[contactPopover setDelegate:self];

}

我在这里错过了什么?因为它运行正常,但只要我点击按钮,应用程序崩溃 . 我认为这是代表问题,但我不确定 . 任何意见,将不胜感激 .

4 回答

  • 1

    我认为这段代码会对你有所帮助 . 你当然缺少委托方法

    ViewController *viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:navigationController];
    popover.delegate = self;
    popover.popoverContentSize = CGSizeMake(644, 425); //your custom size.
    [popover presentPopoverFromRect:button.frame inView:self.view permittedArrowDirections: UIPopoverArrowDirectionLeft | UIPopoverArrowDirectionUp animated:YES];
    

    只要确保你没有忘记UIPopover Delegate方法,否则应用程序肯定会崩溃 . 这是强制性的 .

  • 1
    UIViewController *controller = [[UIViewController alloc] init];
     [view removeFromSuperview]; //view is a view which is displayed in a popover
     controller.view = view;
     UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:controller];
     popover.delegate = self;
    [popover presentPopoverFromRect:button.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    
  • 2

    我所要做的就是在.h文件中将属性从“retain”更改为“strong”并且它可以正常运行,从而阻止应用程序崩溃 .

  • 32

    是的,将“保留”更改为“强”会使您保留选择器视图对象 . 我认为您的代码存在问题,当方法完成时,UIPopoverController对象会自动解除分配 . 制作强大的属性会让你强烈指出一个对象 .

相关问题