ios - 旋转时弹出窗口视图位置错误
问题描述
我可能会尝试将弹出框居中并使其在旋转后仍居中。这项研究几乎回答了我的问题。但是,我注意到一个非常奇怪的问题:当我在设备处于纵向时启动弹出框时,它首先是居中的,但是,如果我旋转到横向,然后将它再次旋转到纵向,它是一个比中心位置高一点。我通过屏幕截图制作了一张照片以表明
左边的截图是正确的位置,在第一次启动popover时出现,右边的截图是错误的位置,你可以通过我画的线清楚地看到它们之间的区别。
这是我用来使弹出框居中的代码
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if let controller = self.presentedViewController as? PopoverController {
controller.popoverPresentationController?.sourceRect = CGRect(x: size.width / 2,
y: size.height / 2,
width: 0, height: 0)
let globalPoint = controller.view.superview?.convert(controller.view.frame.origin, to: nil)
controller.label.text = "x: \(globalPoint!.x), y: \(globalPoint!.y)"
self.view.layoutIfNeeded()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "popoversegue" {
let controller = segue.destination
controller.popoverPresentationController!.delegate = self
controller.popoverPresentationController!.sourceRect = CGRect(x: view.center.x, y: view.center.y,
width: 0, height: 0)
controller.popoverPresentationController?.sourceView = self.view
controller.preferredContentSize = CGSize(width: 500, height: 600)
controller.popoverPresentationController!.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
}
此外,我已经意识到这个问题只发生在纵向,弹出框总是在横向位置很好地居中。这里可能有什么问题?
解决方案
使您的课程符合“UIPopoverPresentationControllerDelegate”
然后添加以下代码。我已经尝试过并且工作正常。
func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) {
let viewFrame = popoverPresentationController.presentingViewController.view.frame
let deltaX = viewFrame.height - rect.pointee.midX
rect.pointee = CGRect(x: viewFrame.width - deltaX, y: rect.pointee.maxY, width: 0, height: 0)
}
推荐阅读
- python - Pytorch BiLSTM POS 标记问题:RuntimeError:input.size(-1) 必须等于 input_size。预期 6,得到 12
- apache-spark - Apache Spark 如何收集和协调来自执行程序的结果
- mysql - 计算和索引一个月的工作日 - mysql
- java - Android PACT 演示应用程序
- testng - 无法在 TestNG 中使用 testng.xml 按组运行测试
- angular - 无法绑定到“routerLinkActiveOptions”,因为它不是已知属性
- java - 添加时间注释,因为日期在 Rest api 请求上跳过 Gson 序列化
- python - 在创建动态网址时,我得到一个带有参数错误的“dashboard_group”的反向
- openshift - 为什么在openshift中rest api没有从3.x升级到4.x?
- c# - 检查所有表中同一列的值[实体框架]