如何让iOS弹出窗口视图在气泡中正确定位

4nkexdtk  于 9个月前  发布在  iOS
关注(0)|答案(1)|浏览(71)

我编写了代码,用于在选中了UICollectionView单元格但由于某种原因不可用时显示该单元格中的弹出框。它工作正常,除了内容从来没有正确定位在弹出气泡。注意,从两个例子显示,内容总是向插入符号移动约一半的插入符号的厚度。

很明显,大小的计算是正确的,但似乎popover控制器只是错误地计算了popupView的位置。由于移动的方向是我无法控制的,我不能只是把所有的东西都移动几个像素作为解决办法。
故事板只是有一个popupView,它带有约束,可以在场景视图中水平和垂直居中:

这是我的代码注意,我已经打开了视图周围的边框,只是为了强调这种变化。

// Inside 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;
}

我已经成功地使用这个公式做了很长一段时间的弹出窗口,然后有一天一些iOS或Xcode更新悄悄地打破了定位(不确定,但我认为这是在iOS 13或14左右)。有人知道我哪里做错了吗?我一直在寻找一个在最新的iOS版本下实现弹出框的完整示例,但在任何地方都找不到。

np8igboo

np8igboo1#

不知道什么时候会改变,什么时候...而且,也许你是“得到幸运”与您的布局,所以你没有注意到它.但是...
我们希望根据控制器的视图的大小设置.preferredContentSize-而不是您的popupView子视图。
此外,我们希望确保内容被限制在 * 安全区域 *。
所以,如果我像这样设置一个MenuUnavailableViewController

“不可用”和“原因:“标签内容拥抱和压缩阻力优先级都设置为Required.

  • Unavailable Lbl标签将确定宽度
  • “原因Lbl`标签将确定高度

在调用控制器中,设置标签的字符串属性。
然后,MenuUnavailableViewController类看起来像这样:

@implementation MenuUnavailableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.unavailableLbl.text = _unavailableString;
    self.reasonLbl.text = _reasonString;
    
    self.preferredContentSize = [self.view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
}

@end

不需要在viewWillAppear中做任何事情。
以下是它的外观(循环通过3组字符串):

如果我们清除颜色和边界:

为了说明它适用于不同的“箭头”方向:

相关问题