我想做的是让POPOVER的左上角与父视图的左上角相等,我试过这样的操作:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 250, y: 250, width: 100, height: 100))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(popover), for: .touchUpInside)
view.addSubview(button)
}
@objc func popover() {
let contentVC = UIViewController()
contentVC.view.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
contentVC.view.backgroundColor = UIColor.blue
contentVC.modalPresentationStyle = .popover
contentVC.preferredContentSize = CGSize(width: 300, height: 300)
let popVC = contentVC.popoverPresentationController
popVC?.sourceView = view
popVC?.sourceRect = CGRect(x: 0, y: 0, width: 300, height: 300)
popVC?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
popVC?.popoverLayoutMargins = .zero
self.present(contentVC, animated: true, completion: nil)
}
然而,结果是这样的:截图看起来像是iOS添加了一些偏移量到popover
我还尝试将modalPresentationStyle更改为overCurrentContext,但它变成了fullscreen。有没有办法使用当前的ViewController来做到这一点?(而不是手动将子视图添加到该位置)
如果我没理解错的话,我很少修改你的代码:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 250, y: 250, width: 100, height: 100))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(popover), for: .touchUpInside)
view.addSubview(button)
}
@objc func popover() {
let ac = UIAlertController(title: "Hello!", message: "This is a test.", preferredStyle: .actionSheet)
let popover = ac.popoverPresentationController
popover?.sourceView = view
popover?.sourceRect = CGRect(x: 32, y: 32, width: 100, height: 100)
present(ac, animated: true)
}