iOS UIObjective C开发

在iPhone上面实现popover菜单

2016-04-24  本文已影响3037人  流星大石头
效果图
2.gif

github链接地址:https://github.com/changanli/Popover

简单介绍

*注意:
如果想要在iphone上面看到popover的效果,首 先需要取消系统默认的自适应效果,iOS系统会根据设 备的不同来进行自适应,因为自适应的modal模式是从底部弹出来。

popover实现菜单效果的步骤
代码实现 Swift3.0 + Xcode8.2.1

class ViewController: UIViewController {
    
    var dest:UIViewController? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.创建目标控制器
        let destVC = UIViewController()
        destVC.view.backgroundColor = UIColor.red
        //2.设置目标控制器Modal出来的样式
        destVC.modalPresentationStyle = .popover
         //3.设置目标控制器Modal出来之后的大小
        destVC.preferredContentSize = CGSize(width:100, height: 200)
        dest = destVC
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        btn.setTitle("全部", for: .normal)
        btn.addTarget(self, action: #selector(ViewController.popover(sender:)), for: .touchUpInside)
        btn.setTitleColor(UIColor.orange, for: .normal)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        
    }
    
    func popover(sender:UIButton) {
       //4.获取目标控制器的popoverPresentationController
        guard let popoverVC = dest!.popoverPresentationController else {
            return
        }
        //5.给popoverVC设置背景颜色
        popoverVC.backgroundColor = UIColor.white
       //5.给popoverPresentationController设置代理
        popoverVC.delegate = self
       //6.设置sourceView和sourceRect
        popoverVC.sourceView = sender
        popoverVC.sourceRect = sender.bounds
         //7.如果sourceView是UIBarButtonItem类型,必须要有下面这一句.这里的sender是UIButton类型的,所已不需要下面这一句
        // popoverVC.barButtonItem = UIBarButtonItem(customView: sender)
       //8.present目标控制器
        present(dest!, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension ViewController:UIPopoverPresentationControllerDelegate {
   //9.在代理方法中将自适应类型设置None
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
}
上一篇下一篇

猜你喜欢

热点阅读