如何使用UIPopoverArrowDirectionRight或UIPopoverArrowDirectionLeft从UITableViewCell正确显示弹出窗口

Ome*_*mer 32 objective-c popover ipad uipopovercontroller

我总是尝试以这种方式从tableView中的单元格呈现一个popover:

[myPopover presentPopoverFromRect:cell.frame inView:self.tableView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Run Code Online (Sandbox Code Playgroud)

但是我不能使用UIPopoverArrowDirectionRight或Left,因为根据ipad(纵向或横向)的位置,popover会出现在其他地方.

我是以正确的方式呈现弹出窗口吗?

PS:表视图位于splitView的detailView中.

小智 49

您是通过rectForRowAtIndexPath方法从单元格中获取帧.这是对的.然而,tableview很可能是更大的iPad视图的子视图,所以当popover获得坐标时,它认为它们在更大的视图中.这就是为什么popover出现在错误的地方.

例如,该行的CGRect是(0,40,320,44).而不是在tableview上定位该框架的popover,而是在主视图上定位该框架.

我通过将帧从表的相对坐标转换为更大视图中的坐标来解决了这个问题.

码:

CGRect aFrame = [self.myDetailViewController.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:theRow inSection:1]];
[popoverController presentPopoverFromRect:[self.myDetailViewController.tableView convertRect:aFrame toView:self.view] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
Run Code Online (Sandbox Code Playgroud)

希望能帮助其他人搜索此问题.


ant*_*kes 22

我今天遇到了这个问题,我找到了一个更简单的解决方案.
在实例化弹出窗口时,您需要指定单元格的内容视图:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *aViewController = [[UIViewController alloc] init];
    // initialize view here

    UIPopoverController *popoverController = [[UIPopoverController alloc] 
        initWithContentViewController:aViewController];
    popoverController.popoverContentSize = CGSizeMake(320, 416);
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [popoverController presentPopoverFromRect:cell.bounds inView:cell.contentView 
        permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

    [aView release];
    // release popover in 'popoverControllerDidDismissPopover:' method
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*ust 20

在Swift中,在上述答案之间,这适用于我在iPad上的任何方向:

if let popOverPresentationController : UIPopoverPresentationController = myAlertController.popoverPresentationController {

    let cellRect = tableView.rectForRowAtIndexPath(indexPath)

    popOverPresentationController.sourceView                = tableView
    popOverPresentationController.sourceRect                = cellRect
    popOverPresentationController.permittedArrowDirections  = UIPopoverArrowDirection.Any

}
Run Code Online (Sandbox Code Playgroud)


小智 1

这是对我来说效果很好的简单解决方案

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    CGRect rect=CGRectMake(cell.bounds.origin.x+600, cell.bounds.origin.y+10, 50, 30);
    [popOverController presentPopoverFromRect:rect inView:cell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

}
Run Code Online (Sandbox Code Playgroud)

  • 大多数人不应该这样做。永远不要使用这样的硬编码数字,当方向改变时这将不起作用。 (43认同)