利用UIPopoverPresentationController实现弹窗

iOS8之后新增了UIPopoverPresentationController,可以实现类似于iPad的UIPopoverController.
Demo地址

第一步:
打开Main.storyboard,在默认的ViewController中添加一个UIButton,然后新建一个UIView
Controller,并将UIButton的action事件指向新创建的ViewController.
如下图所示:

利用UIPopoverPresentationController实现弹窗_第1张图片
Main.storyboard示例图.png

第二步:
打开ViewController.swift,并添加代码.

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    @IBOutlet weak var button: UIButton!
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let vc = segue.destination
        vc.modalPresentationStyle = .popover
        //箭头所指区域
        vc.popoverPresentationController?.sourceView = button
        vc.popoverPresentationController?.sourceRect = button.bounds
        //箭头方向
        vc.popoverPresentationController?.permittedArrowDirections = .up
        //设置代理
        vc.popoverPresentationController?.delegate = self
        //弹出窗口大小
        vc.preferredContentSize = CGSize(width: 200, height: 300)
    }
    
    //iPhone下默认是.overFullScreen(全屏显示),需要返回.none,否则,没有弹窗效果。iPad不需要
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    
}

注意事项:

  • 遵守UIPopoverPresentationControllerDelegate代理
  • 实现adaptivePresentationStyle代理方法,并返回.none.(iPhone下默认是.overFullScreen)
  • 如果按钮不是UIButtton,而是导航栏上的UIBarButtonItem.由于该控件没有指定的frame,无法设置sourceViewsourceRect,将箭头所指区域下的两行代码修正一下即可:
    vc.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem;
利用UIPopoverPresentationController实现弹窗_第2张图片
弹窗效果.png

你可能感兴趣的:(利用UIPopoverPresentationController实现弹窗)