【问题标题】:ios 9 UIPopoverPresentationController constant placement on rotationios 9 UIPopoverPresentationController 在旋转时不断放置
【发布时间】:2016-09-09 15:49:13
【问题描述】:

在 iOS9 中,当我使用 UIPopoverPresentationController 旋转屏幕时,坐标会重置为 0,并且不会附加到作为按钮的 sourceView。

我试过了:

func popoverPresentationController(popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer, inView 视图: AutoreleasingUnsafeMutablePointer) { rect.initialize(CGRectMake(200, 200, 400, 400)) }

但无济于事。有什么帮助吗?

【问题讨论】:

  • rect.initialize(CGRectMake(200, 200, 400, 400) 真的吗?如果那是你的代码,难怪什么都没有发生。

标签: ios swift uipopovercontroller


【解决方案1】:

您可以对 sourceView 按钮应用约束,然后将其用作弹出源:

myPopoverViewController.popoverPresentationController?.sourceView = button

你也可以在storyboard中设置sourceView,但是sourceRect需要在代码中设置:

myPopoverViewController.popoverPresentationController?.sourceRect = button.bounds

您需要正确的源矩形才能使弹出箭头正确对齐。 现在您不需要关闭并在旋转时呈现弹出框。 UIPopoverPresentationController 会为你做到这一点。一旦在创建弹出框时设置了 sourceView/sourceRect,您甚至不需要更新它们。

使用viewWillTransition 捕捉大小和方向变化:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { _ in
        if self.popover != nil {
            // optionally scroll to popover source rect, if inside scroll view
            let rect = ...
            self.scrollView.scrollRectToVisible(rect, animated: false)

            // update source rect constraints
            buttonConstraint.constant = ...
            button.setNeedsLayout()
            button.layoutIfNeeded()
        }
    }, completion: nil)
}

解释: animate(alongsideTransition: ((UIViewControllerTransitionCoordinatorContext) -> Void)?, completion: ((UIViewControllerTransitionCoordinatorContext) -> Void)? = nil) 的诀窍是你应该在alongsideTransition 闭包中更新你的约束,而不是在completion 中。这样可以确保在旋转结束时恢复弹出框时 UIPopoverPresentationController 具有更新的 sourceRect。

可能看起来违反直觉的是,在 alongsideTransition 闭包中,您已经有了新的布局,您可以从中导出约束计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多