iOS類似氣泡彈窗的系統實現方法(UIPopoverPresentationController)

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
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前言 最近項目有一個需求需要實現一個類似氣泡的popover彈窗,就是點擊一個按鈕的時候在按鈕的某一個方向彈出一個...
    alpha_feng閱讀 3,330評論 0 2
  • 夜鶯2517閱讀 127,752評論 1 9
  • 版本:ios 1.2.1 亮點: 1.app角標可以實時更新天氣溫度或選擇空氣質量,建議處女座就不要選了,不然老想...
    我就是沉沉閱讀 6,939評論 1 6
  • 我是一名過去式的高三狗,很可悲,在這三年里我沒有戀愛,看著同齡的小伙伴們一對兒一對兒的,我的心不好受。怎么說呢,高...
    小娘紙閱讀 3,414評論 4 7
  • 那一年,我選擇了獨立遠行,火車帶著我在前進的軌道上爬行了超過23個小時; 那一年,我走過泥濘的柏油路,在那個遠離故...
    木芽閱讀 1,656評論 4 5