如何从UITableViewCell.accessoryView调用PopOver控制器?

Vic*_*Vic 3 objective-c uitableview ipad uipopovercontroller

首先我想说的是我对ipad/ipod/iphone开发很新,对于objective-c也是如此.

话虽如此,我正在尝试开发一个针对iPad的小应用程序,使用Xcode和IB,基本上,我有一个表,对于表中的每个UITableViewCell,我在accessoryView中添加了一个包含图像的按钮.

这是代码:

UIImage *img = [UIImage imageNamed:@"myimage.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, img.size.width, img.size.height);
button.frame = frame;   // match the button's size with the image size

[button setBackgroundImage:img forState:UIControlStateNormal];

// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
[button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
Run Code Online (Sandbox Code Playgroud)

到目前为止,这么好,现在问题是当用户点击单元的accessoryView上的按钮时,我想要一个PopOver控件出现.

我在tableView的"accessoryButtonTappedForRowWithIndexPath"上尝试了这个:

UITableViewCell *cell = [myTable cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;

//customViewController is the controller of the view that I want to be displayed by the PopOver controller
customViewController = [[CustomViewController alloc]init];

popOverController = [[UIPopoverController alloc]
initWithContentViewController: customViewController];

popOverController.popoverContentSize = CGSizeMake(147, 122);

CGRect rect = button.frame;

[popOverController presentPopoverFromRect:rect inView:cell.accessoryView
permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
Run Code Online (Sandbox Code Playgroud)

这段代码的问题是它在应用程序View的顶部显示了Popover,而调试时我看到了"rect"的值,它们是:

x = 267
y = 13
Run Code Online (Sandbox Code Playgroud)

所以我认为很明显为什么PopOver会在视图中显示出来,所以我的问题是,如何才能让PopOver的正确值显示在单元的accessoryView上的按钮下方?

另外,正如你所看到的,我告诉它使用"cell.accessoryView"作为"inView:"属性,这样可以吗?

小智 8

尝试使用button.bounds而不是button.frame因为rect是相对于inView.

另请注意,如果单元格靠近屏幕底部,则弹出窗口可能无法以正确的大小显示,因为您正在向上方向强制箭头.你应该手动处理这个或者只使用Any.