关于ios:如何以编程方式从uibutton以编程方式显示弹出框(不使用界面构建器)

How to display a popover programmatically from a uibutton that is also created programmatically (Not using interface builder)

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

在视图中创建的按钮在我的视图控制器中加载。

1
2
3
4
5
6
7
8
9
10
11
12
13
 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];

然后我有了按下按钮时使用的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-(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];

}

我这里缺什么?因为它运行良好,但只要我点击按钮,应用程序就会崩溃。我认为这是代表性问题,但我不确定。任何建议都将不胜感激。


我想这个密码对你有帮助。您肯定缺少委托方法

1
2
3
4
5
6
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委托方法,否则应用程序肯定会崩溃。这是强制性的。


1
2
3
4
5
6
 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];


是的,将"retain"的属性更改为"strong"会使您保留选取器视图对象。我认为您的代码的问题是,当方法完成时,uipopOverController对象会自动释放。使强属性使您能够强指向对象。


我所要做的就是将.h文件中的属性从"retain"改为"strong",它工作正常,阻止了应用程序崩溃。