iOS上類似微信右上角的氣泡彈窗,使用系統提供的api實現如下(三角箭頭的目前居中,如何實現偏移,目前沒找到方法)。
Ex1氣泡.jpg
// 在iPad端只實現本方法即可顯示氣泡彈窗,在iPhone上需要實現下面的代理方法并返回 .none 才可以。
@objc private func button2Action(sender: UIButton) {
// 彈出氣泡的控制器
let vc = UIViewController()
vc.view.backgroundColor = .red
// 設置彈出樣式
vc.modalPresentationStyle = .popover
// 設置彈出窗口的大小
vc.preferredContentSize = CGSize(width: 100, height: 100)
let popoverPresentation = vc.popoverPresentationController
popoverPresentation?.sourceView = sender // 箭頭指向的view
// 彈出界面的起點(箭頭指向的起點)。
// 當箭頭朝上時(.up)看效果是以指向的 sender起點為原點,最終箭頭坐標為(boubds.x + bounds.width/2, bounds.y + bounds.height/2)
popoverPresentation?.sourceRect = sender.bounds
// popoverPresentation?.popoverLayoutMargins = UIEdgeInsets(top: 10, left: 110, bottom: 10, right: 10)
// 彈窗默認帶的箭頭方向(整個彈窗方向也會隨之變化)
popoverPresentation?.permittedArrowDirections = .up
popoverPresentation?.backgroundColor = .green
// iPhone上若要展示氣泡彈窗需實現此代理的一個方法
popoverPresentation?.delegate = self
present(vc, animated: true, completion: nil)
}
/// 在iPhone上若要實現氣泡彈窗,需要實現此方法并且返回 .none,否則彈出界面會充滿全屏
/// 此方法為 UIAdaptivePresentationControllerDelegate 協議提供的方法,UIPopoverPresentationControllerDelegate協議遵循此協議
/// - Parameter controller:
/// - Returns: .none
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
print("++++++++++++++++++")
return .none
}
如上代碼實現的效果如下圖Ex3氣泡
Ex2氣泡.jpg