You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让iOS Popover视图在气泡内实现正确定位

iOS Popover内容偏移问题

我编写了代码,在UICollectionView单元格被选中但不可用时,从该单元格弹出Popover。功能正常,但Popover气泡内的内容始终无法正确定位——从以下示例可见,内容总是朝向箭头偏移约箭头厚度的一半。

内容偏移示例1
内容偏移示例2

尺寸计算显然是正确的,但Popover控制器似乎错误计算了popupView的位置。由于偏移方向不受控制,无法通过固定像素偏移作为临时解决方法。

故事板中仅给popupView设置了约束,使其在场景视图内水平和垂直居中:

popupView约束设置

以下是我的代码(已开启视图边框来突出偏移问题):

collectionView:didSelectItemAtIndexPath: 中的代码

UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
MenuUnavailableViewController* muc = [mainStoryboard instantiateViewControllerWithIdentifier:@"MenuOptionUnavailable"];
muc.modalPresentationStyle = UIModalPresentationPopover;

[self presentViewController:muc animated:NO completion:nil];

MenuCollectionViewCell* menuCell = (MenuCollectionViewCell*) [menuCollection cellForItemAtIndexPath:indexPath];
muc.popoverPresentationController.sourceView = menuCollection;
muc.popoverPresentationController.sourceRect = menuCell.frame;
muc.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
@implementation MenuUnavailableViewController

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    [self.view layoutSubviews];
    self.preferredContentSize = self.popupView.bounds.size;
    self.popupView.layer.borderColor = [UIColor blackColor].CGColor;
    self.popupView.layer.borderWidth = 2;
    self.popupView.layer.cornerRadius = 12;
}

我此前一直用该方式成功实现Popover,但某次iOS或Xcode更新后(推测是iOS13或14版本),这个定位问题悄然出现。有人知道问题出在哪吗?我一直在寻找适配新版iOS的Popover完整示例,但始终未找到。

内容的提问来源于stack exchange,提问作者Agent Friday

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:05:09