UIPopoverPresentationController on iPhone doesn't produce popover - ios

I'm trying to implement the new UIPopoverPresentationController in my iPhone app (using Objective C). What I want is a simple popover with a tableview that emanates from the initiating button.
--Edit--
Here's my REVISED code, adapted from research in the docs, SO, and from input in comments below:
- (IBAction)selectCategoryBtn:(UIButton *)sender
{
[self performSegueWithIdentifier:#"CatSelectSegue" sender:self.selCatButton];
}
-(void) prepareForSegue:(UIStoryboardSegue *) segue Sender:(id) sender
{
if (sender == self.selCatButton)
{
if ([segue.identifier isEqualToString:#"CatSelectSegue"])
{
UIPopoverPresentationController *controller = segue.destinationViewController;
controller.delegate = self;
controller.sourceView = self.selCatButton;
controller.sourceRect = self.selCatButton.frame;
}
}
}
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
return UIModalPresentationNone;
Here's my storyboard hookup:
However this simply presents a tableview in a modal fashion, rising up from the bottom and consuming the entire screen.
I've googled, and looked all over SO, but it appears that I'm not the only one confused by what I'd hoped would resolve a nettlesome issue for the iPhone.
Can anyone see a glitch in my code or direct me to a clear tutorial? I've looked, but maybe the API is just so new nobody's got a handle on it yet.
Thanks!
2nd edit:
Here's what gets presented as a result of the code above. I reduced the size of the tableview in the View Controller I expected to be presented as a popover. I colored the background gray, just to clarify what's showing up instead of the popover.

Steps:
A) Link your UIButton to the popover's view controller using the Present As Popover segue type. I actually had to create a new project to get this to appear but it's probably something to do with the base SDK.
B) Make the View Controller containing the UIButton conform to the <UIPopoverPresentationControllerDelegate>. E.g. In your MyViewController.m file add:
#interface MyViewController () <UIPopoverPresentationControllerDelegate>
C) Add the method below to the View Controller containing the UIButton:
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
return UIModalPresentationNone;
}
D) Add the following into your prepareForSegue:sender: replacing your segue.identifier check:
if ([segue.identifier isEqualToString:#"CatSelectSegue"]) {
UIViewController *dvc = segue.destinationViewController;
UIPopoverPresentationController *controller = dvc.popoverPresentationController;
if (controller) {
controller.delegate = self;
}
}
Code tested and proof it works:
Edit: My test app TPOPViewController.m file where the magic happens:
#import "TPOPViewController.h"
#interface TPOPViewController () <UIPopoverPresentationControllerDelegate>//, UIAdaptivePresentationControllerDelegate>
#end
#implementation TPOPViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSString *identifier = segue.identifier;
if ([identifier isEqualToString:#"popover"]) {
UIViewController *dvc = segue.destinationViewController;
UIPopoverPresentationController *ppc = dvc.popoverPresentationController;
if (ppc) {
if ([sender isKindOfClass:[UIButton class]]) { // Assumes the popover is being triggered by a UIButton
ppc.sourceView = (UIButton *)sender;
ppc.sourceRect = [(UIButton *)sender bounds];
}
ppc.delegate = self;
}
}
}
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
return UIModalPresentationNone;
}
#end
My test storyboard as well:

Apparently the above method no longer works with iOS9/Xcode7. This is because if you set the segue style to "Popover" using Interface Builder, Xcode ignores it when it compiles your application. Furthermore, it automatically sets the segue back to "Push" the next time you open your project. If you have version control software like Git, you'll be able to observe this unwanted change being made.
However, it's still possible to get iPad-style popovers on the iPhone if you manually present the view controller that you want to show as a popover. Example Swift code:
// ViewController.swift
// PopoverDemo
//
// Created by bhnascar on 12/2/15.
// Copyright © 2015 bhnascar. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
/* The bar button item that will present the popover. */
var popoverButton: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
popoverButton = UIBarButtonItem(title: "Pop!", style: UIBarButtonItemStyle.Plain, target: self, action: "presentPopover")
self.navigationItem.rightBarButtonItem = popoverButton
}
// Mark: - UIPopoverPresentationControllerDelegate
func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) {
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.barButtonItem = popoverButton
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
// Mark: - Callback function for popover button.
func presentPopover() {
let popoverContentController = UIViewController()
popoverContentController.view.backgroundColor = .blue
// Set your popover size.
popoverContentController.preferredContentSize = CGSize(width: 300, height: 300)
// Set the presentation style to modal so that the above methods get called.
popoverContentController.modalPresentationStyle = .popover
// Set the popover presentation controller delegate so that the above methods get called.
popoverContentController.popoverPresentationController!.delegate = self
// Present the popover.
self.present(popoverContentController, animated: true, completion: nil)
}
}

SWIFT 3.X
This will show the popover at the center of the screen
class CommonViewController: UIViewController, UIPopoverPresentationControllerDelegate{
func adaptivePresentationStyle(
for controller: UIPresentationController,
traitCollection: UITraitCollection)
-> UIModalPresentationStyle {
return .none
}
func showPopover() {
let myViewController = UIViewController()
myViewController.preferredContentSize = CGSize(width: 320, height: 200)
myViewController.modalPresentationStyle = .popover
let popOver = myViewController.popoverPresentationController
popOver?.delegate = self
self.present(myViewController, animated: true, completion: nil)
popOver?.permittedArrowDirections = .up
popOver?.sourceView = self.view
let rect = CGRect(
origin: CGPoint(x: self.view.frame.width/2,
y: self.view.frame.height/2),
size: CGSize(width: 1, height: 1)
)
popOver?.sourceRect = rect
}
}

To present UIModalPresentationStyle popover from iPhone/iPad:
-(void)menuButtonPressed:(UIButton *)sender {
self.menuPopoverController = [[DownloadMenuPopoverController alloc] initWithStyle:UITableViewStylePlain];
self.menuPopoverController.delegate = self;
self.menuPopoverController.modalPresentationStyle = UIModalPresentationPopover;
self.menuPopoverController.popoverPresentationController.delegate = self;
self.menuPopoverController.preferredContentSize = CGSizeMake(250,80);
self.menuPopoverController.popoverPresentationController.sourceRect = sender.frame;// rect to show view
self.menuPopoverController.popoverPresentationController.sourceView = self.view;
UIPopoverPresentationController *popPC = self.menuPopoverController.popoverPresentationController;
popPC.permittedArrowDirections = UIPopoverArrowDirectionAny;
popPC.delegate = self;
[self presentViewController:self.menuPopoverController animated:YES completion:nil];
}
#pragma mark - UIPresentationController Delegate methods
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(UITraitCollection *)traitCollection {
return UIModalPresentationNone;
}
- (UIViewController *)presentationController:(UIPresentationController *)controller viewControllerForAdaptivePresentationStyle:(UIModalPresentationStyle)style {
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller.presentedViewController];
return navController;
}

**Made a barbutton item like this** -
let dotImage = UIImage(named: "dot")?.withRenderingMode(.alwaysOriginal) let searchImage = UIImage(named: "search")?.withRenderingMode(.alwaysOriginal) // let shareImageButton = UIBarButtonItem(image: shareImage, style: .plain, target: self, action: #selector(didTapshareImageButton(sender:))) let dotImageButton = UIBarButtonItem(image: dotImage, style: .plain, target: self, action: #selector(didTapdotImageButton(sender:))) let searchButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(didTapSearchButton(sender:)))
**Added popover on this -**
#objc func didTapdotImageButton(sender: UIBarButtonItem){
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ShareVC")
vc.modalPresentationStyle = .popover
let popover: UIPopoverPresentationController = vc.popoverPresentationController!
popover.barButtonItem = sender
popover.delegate = self
sender.image = UIImage(named: "close")?.withRenderingMode(.alwaysOriginal)
present(vc, animated: true, completion:nil)
}

Related

UIPopoverPresentationController on iPhone with iOS 10

I'm trying to display a ViewController as a popover on an iPhone. I have already been through several answers on SO and the rest of the web but none have worked so far. I wrote a simple app to test this.
ViewController.swift:
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(clicked(_:)))
}
func clicked(_ sender: Any) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.blue
vc.preferredContentSize = CGSize(width: 200, height: 200)
vc.modalPresentationStyle = .popover
present(vc, animated: true, completion: nil)
let ppc = vc.popoverPresentationController
ppc?.permittedArrowDirections = .any
ppc?.delegate = self
ppc?.barButtonItem = navigationItem.rightBarButtonItem
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
The storyboard has an empty ViewController embedded in a NavigationController.
Running this, I expected a popover view controller to show under the "done" button. Instead, the blue view controller is presented full screen.
Is there a way to change this behaviour?
You are connecting delegate after presenting view. How it will return .none from delegate and show as popover. Use this :-
func clicked(_ sender: Any) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.blue
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 200, height: 200)
let ppc = vc.popoverPresentationController
ppc?.permittedArrowDirections = .any
ppc?.delegate = self
ppc?.barButtonItem = navigationItem.rightBarButtonItem
ppc?.sourceView = sender
present(vc, animated: true, completion: nil)
}
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(clicked(_:)))
}
func clicked(_ sender: Any) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.blue
vc.preferredContentSize = CGSize(width: 200, height: 200)
vc.modalPresentationStyle = .popover
let ppc = vc.popoverPresentationController
ppc?.permittedArrowDirections = .any
ppc?.delegate = self
ppc!.sourceView = sender as? UIView
ppc?.barButtonItem = navigationItem.rightBarButtonItem
present(vc, animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
The solutions above no longer work in recent iOS versions 12 and above. To get it working again, override -modalPresentationStyle within the viewController to be presented as a popover and return UIModalPresentationPopover.
Additionally provide a popoverPresentationController.delegate, implement adaptivePresentationStyleForPresentationController:traitCollection: and return UIModalPresentationNone.
#interface PopoverViewController : UIViewController
#end
#implementation PopoverViewController
- (UIModalPresentationStyle)modalPresentationStyle
{
return UIModalPresentationPopover;
}
#end
#interface ViewController ()<UIPopoverPresentationControllerDelegate>
#end
#implementation ViewController
- (IBAction)openPopover:(id)sender
{
UIViewController* testVC = [[PopoverViewController alloc] init];
testVC.view.backgroundColor = UIColor.yellowColor;
UIPopoverPresentationController* popPresenter = [testVC popoverPresentationController];
popPresenter.permittedArrowDirections = UIPopoverArrowDirectionUp;
popPresenter.delegate = self;
popPresenter.sourceView = sender;
popPresenter.sourceRect = [sender bounds];
[self presentViewController:testVC animated:YES completion:^{}];
}
#pragma mark protocol (UIPopoverPresentationControllerDelegate)
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(UITraitCollection *)traitCollection
{
return UIModalPresentationNone;
}
#end
Add:
vc.popoverPresentationController?.delegate = self
just before the line:
present(vc, animated: true, completion: nil)

How to use dismiss an iPhone popover in a Storyboard

I would like to use the solution provided by Travis M. to this question:
How to use dismiss an iPhone popover in an Adaptive Storyboard
However, I would need the below be translated to objective c.
Anyone could help out?
If what you want is a popover on your iPad but a modal sheet with a close button on your iPhone then you can do it without creating an extra navigation controller in storyboard for the popover.
In Xcode 6.3 storyboard, you simply hook up a view controller and designate the segue as a "Present as Popover"
The code below should go in the view controller that segues to the popover, not in the popover itself:
First you set up the popover delegate:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "myPopoverSegueName") {
let vc = segue.destinationViewController
vc.popoverPresentationController?.delegate = self
return
}
}
Then you add the delegate extension (below your view controller's code) and create the navigation controller / close button on the fly:
extension myViewController: UIPopoverPresentationControllerDelegate {
func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
let btnDone = UIBarButtonItem(title: "Done", style: .Done, target: self, action: "dismiss")
let nav = UINavigationController(rootViewController: controller.presentedViewController)
nav.topViewController.navigationItem.leftBarButtonItem = btnDone
return nav
}
}
Then you add the delegate extension (below your view controller's code) and create the navigation controller / close button on the fly:
extension myViewController: UIPopoverPresentationControllerDelegate {
func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
let btnDone = UIBarButtonItem(title: "Done", style: .Done, target: self, action: "dismiss")
let nav = UINavigationController(rootViewController: controller.presentedViewController)
nav.topViewController.navigationItem.leftBarButtonItem = btnDone
return nav
}
}
Then you add your dismiss function and you should be good to go:
func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
It's not that different from objective-c. You could probably figure out what's going on just by looking at it. It's just setting up prepare for segue and implementing part of a protocol.
myViewController needs to declare itself as conforming to UIAdaptivePresentationControllerDelegate. Then this is the code.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"myPopoverSegueName"]) {
UIViewController *viewController = segue.destinationViewController;
viewController.popoverPresentationController.delegate = self
}
}
- (UIViewController *)presentationController:(UIPresentationController *)controller
viewControllerForAdaptivePresentationStyle:(UIModalPresentationStyle)style
{
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(dismiss)];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller.presentedViewController];
navController.topViewController.navigationItem.leftBarButtonItem = doneButton;
}
-(void) dismiss
{
[self dismissViewControllerAnimated:YES completion:nil];
}
You don't need to use an extension or category. Not going to vouch for whether this does what Travis M. says it does.

How to present popover properly in iOS 8

I'm trying to add a UIPopoverView to my Swift iOS 8 app, but I am unable to access the PopoverContentSize property, as the popover does not show in the correct shape. my code:
var popover: UIPopoverController? = nil
func addCategory() {
var newCategory = storyboard.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: newCategory)
popover = UIPopoverController(contentViewController: nav)
popover!.setPopoverContentSize(CGSizeMake(550, 600), animated: true)
popover!.delegate = self
popover!.presentPopoverFromBarButtonItem(self.navigationItem.rightBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
output:
When I am doing the same thing through UIPopoverPresentationController, I still don't get it done. this is my code:
func addCategory() {
var popoverContent = self.storyboard.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
var popover = nav.popoverPresentationController as UIPopoverPresentationController
popover.delegate = self
popover.popoverContentSize = CGSizeMake(1000, 300)
popover.sourceView = self.view
popover.sourceRect = CGRectMake(100,100,0,0)
self.presentViewController(nav, animated: true, completion: nil)
}
I get the exact same output.
How do I customize the size of my popover? Any help would be highly appreciated!
Okay, A housemate took a look at it and figured it out:
func addCategory() {
var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSizeMake(500,600)
popover.delegate = self
popover.sourceView = self.view
popover.sourceRect = CGRectMake(100,100,0,0)
self.presentViewController(nav, animated: true, completion: nil)
}
That's the way.
You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize
Actually it is much simpler than that. In the storyboard you should make the viewcontroller you want to use as popover and make a viewcontroller class for it as usual. Make a segue as shown below from the object you want to open the popover, in this case the UIBarButton named "Config".
In the "mother viewcontroller" implement the UIPopoverPresentationControllerDelegate and the delegate method:
func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
//do som stuff from the popover
}
Override the prepareForSeque method like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//segue for the popover configuration window
if segue.identifier == "yourSegueIdentifierForPopOver" {
if let controller = segue.destinationViewController as? UIViewController {
controller.popoverPresentationController!.delegate = self
controller.preferredContentSize = CGSize(width: 320, height: 186)
}
}
}
And you're done. And you can now treat the popover view as any other view, ie. add fields and what not! And you get hold of the the content controller by using the popoverPresentationController.presentedViewController method in the UIPopoverPresentationController.
Also on an iPhone you would have to overwrite
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
I found a complete example of how to get this all to work so that you can always display a popover no matter the device/orientation https://github.com/frogcjn/AdaptivePopover_iOS8_Swift.
The key is to implement UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(PC: UIPresentationController!) -> UIModalPresentationStyle {
// This *forces* a popover to be displayed on the iPhone
return .None
}
Then extend the example above (from Imagine Digital):
nav.popoverPresentationController!.delegate = implOfUIAPCDelegate
Swift 2.0
Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.
import UIKit
class PopOverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSizeMake(200, 200)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")
}
func dismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
See ViewController:
// ViewController.swift
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
func showPopover(base: UIView)
{
if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .Popover
if let pctrl = navController.popoverPresentationController {
pctrl.delegate = self
pctrl.sourceView = base
pctrl.sourceRect = base.bounds
self.presentViewController(navController, animated: true, completion: nil)
}
}
}
override func viewDidLoad(){
super.viewDidLoad()
}
#IBAction func onShow(sender: UIButton)
{
self.showPopover(sender)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !
In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,
- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:#"popover"];
viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }
Here i Convert "Joris416" Swift Code to Objective-c,
-(void) popoverstart
{
ViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:#"PopoverView"];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:controller];
nav.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popover = nav.popoverPresentationController;
controller.preferredContentSize = CGSizeMake(300, 200);
popover.delegate = self;
popover.sourceView = self.view;
popover.sourceRect = CGRectMake(100, 100, 0, 0);
popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:nav animated:YES completion:nil];
}
-(UIModalPresentationStyle) adaptivePresentationStyleForPresentationController: (UIPresentationController * ) controller
{
return UIModalPresentationNone;
}
Remember to ADD
UIPopoverPresentationControllerDelegate, UIAdaptivePresentationControllerDelegate
This is best explained on the iOS8 Day-by-Day blog
In short, once you've set your UIViewController's modalPresentationStyle to .Popover, you can get hold of a UIPopoverPresentationClass (a new iOS8 class) via the controller's popoverPresentationController property.
I made an Objective-C version of Imagine Digitals swift answer above. I don't think I missed anything as it seems to work under preliminary testing, if you spot something let me know, and I'll update it
-(void) presentPopover
{
YourViewController* popoverContent = [[YourViewController alloc] init]; //this will be a subclass of UIViewController
UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:popoverContent];
nav.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController* popover = nav.popoverPresentationController;
popoverContent.preferredContentSize = CGSizeMake(500,600);
popover.delegate = self;
popover.sourceRect = CGRectMake(100,100,0,0); //I actually used popover.barButtonItem = self.myBarButton;
[self presentViewController:nav animated:YES completion:nil];
}
my two cents for xcode 9.1 / swift 4.
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
override func viewDidLoad(){
super.viewDidLoad()
let when = DispatchTime.now() + 0.5
DispatchQueue.main.asyncAfter(deadline: when, execute: { () -> Void in
// to test after 05.secs... :)
self.showPopover(base: self.view)
})
}
func showPopover(base: UIView) {
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "popover") as? PopOverViewController {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .popover
if let pctrl = navController.popoverPresentationController {
pctrl.delegate = self
pctrl.sourceView = base
pctrl.sourceRect = base.bounds
self.present(navController, animated: true, completion: nil)
}
}
}
#IBAction func onShow(sender: UIButton){
self.showPopover(base: sender)
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
return .none
}
and experiment in:
func adaptivePresentationStyle...
return .popover
or:
return .pageSheet....
and so on..
Implement UIAdaptivePresentationControllerDelegate in your Viewcontroller.
Then add :
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{
return .none
}
The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/
In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:
func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
if let popoverController = popoverViewController.popoverPresentationController {
popoverController.delegate = self
popoverController.sourceView = originView
popoverController.sourceRect = originView.bounds
popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
}
self.present(popoverViewController, animated: true)
}
A lot of this was already covered in the answer from #mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.
It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:
func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
if traitCollection.horizontalSizeClass == .compact {
return UIModalPresentationStyle.none
//return UIModalPresentationStyle.fullScreen
}
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
switch style {
case .fullScreen:
let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
return navigationController
default:
return controller.presentedViewController
}
}
// As of Swift 4, functions used in selectors must be declared as #objc
#objc private func doneWithPopover() {
self.dismiss(animated: true, completion: nil)
}
Hope this helps.
var popoverContent = (self.storyboard?.instantiateViewController(withIdentifier: "WhatsNewViewController"))! as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSize(width: 500, height: 100)
popover?.delegate = self
popover?.sourceView = self.view
popover?.sourceRect = CGRectMake(100,100,0,0)
self.present(nav, animated: true, completion: nil)
For those who wants to study!
I created an Open Source project for those who want to study and use Popover view for anypurpose. You can find the project here. https://github.com/tryWabbit/KTListPopup

How do I get a Storyboard-created UIViewController without using seagues into a UIPopover?

I have an iPad app (XCode 4.6, iOS 6.2, Storyboards, ARC) where I created a UIViewController (not connected to any segue) to be used in a UIPopover. These are the ViewController settings:
I have this code that is supposed to display the "viewForPopover" ViewController from within a UIPopover.
UIView *anchor = textField;
UIViewController *viewControllerForPopover =
[self.storyboard instantiateViewControllerWithIdentifier:#"viewForPopover"];
popover = [[UIPopoverController alloc]
initWithContentViewController:viewControllerForPopover];
[popover presentPopoverFromRect:anchor.frame
inView:anchor.superview
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
My problem is: there is no self.storyboard. So how am I supposed to get to the view controller which lies outside of the current class? (current class is a subview of UIView)
Call this method on UIStoryboard:
+ (UIStoryboard *)storyboardWithName:(NSString *)name bundle:(NSBundle *)storyboardBundleOrNil
probably like this if your view controller live in 'MainStoryboard.storyboard':
UIViewController *viewControllerForPopover =
[[UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil]instantiateViewControllerWithIdentifier:#"viewForPopover"];
utility function for swift:
extension UIViewController {
func presentMyCtl( pushed: Bool){
let VC = MyController(nibName: "MyController", bundle: nil)
if pushed{
let nc = self.navigationController!
nc.pushViewController(VC, animated: true)
}else{
self.present(VC, animated: true, completion: nil)
}
}
func dismissMyCtl(pushed: Bool){
if pushed{
let nc = self.navigationController!
nc.popViewController(animated: true)
}else{
self.dismiss(animated: true, completion: nil)
}
}
}
where MyController.swift if the swift file for class, and MyController.xib is the file containing the UI.

Switching ViewControllers with UISegmentedControl in iOS5

I am trying something very simple but somehow I can't get it to work. All I try to do is switching between 2 View Controllers using an UISegmentedControl as you can see it for example in the App Store application in the Highlights tab.
I am using iOS5 and Storyboards.
Here's my Storyboad line up:
So I have a root View Controller and two UITableViews - This 2 TableViews I want to switch.
Here's how the implementation file looks like
#import "SegmentedLocationViewController.h"
#import "PastEventsLocationViewController.h"
#import "FutureEventsLocationViewController.h"
#interface SegmentedLocationViewController()
#property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
#property (strong, nonatomic) NSArray *viewControllers;
#end
#implementation SegmentedLocationViewController
#synthesize segmentedControl = _segmentedControl;
#synthesize viewControllers = _viewControllers;
- (IBAction)indexDidChangeForSegmentedControl:(UISegmentedControl*)segmentedControl
{
NSLog(#"index: %d", segmentedControl.selectedSegmentIndex);
}
- (void)setupViewControllers
{
PastEventsLocationViewController *pastEventsLocationViewController = [[PastEventsLocationViewController alloc] initWithStyle:UITableViewStylePlain];
FutureEventsLocationViewController *futureEventsLocationViewController = [[FutureEventsLocationViewController alloc] initWithStyle:UITableViewStylePlain];
self.viewControllers = [NSArray arrayWithObjects:pastEventsLocationViewController, futureEventsLocationViewController, nil];
}
- (void)setupUI
{
[self.segmentedControl addTarget:self action:#selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupViewControllers];
[self setupUI];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
I can trigger the switch event and can log the currently selected index. But I don't have any idea where to go from here.
Maybe someone can turn my attention towards a certain direction...?
This code works pretty well for your purpose, I use it for one of my new apps.
It uses the new UIViewController containment APIs that allow UIViewControllers inside your own UIViewControllers without the hassles of manually forwarding stuff like viewDidAppear:
- (void)viewDidLoad {
[super viewDidLoad];
// add viewController so you can switch them later.
UIViewController *vc = [self viewControllerForSegmentIndex:self.typeSegmentedControl.selectedSegmentIndex];
[self addChildViewController:vc];
vc.view.frame = self.contentView.bounds;
[self.contentView addSubview:vc.view];
self.currentViewController = vc;
}
- (IBAction)segmentChanged:(UISegmentedControl *)sender {
UIViewController *vc = [self viewControllerForSegmentIndex:sender.selectedSegmentIndex];
[self addChildViewController:vc];
[self transitionFromViewController:self.currentViewController toViewController:vc duration:0.5 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
[self.currentViewController.view removeFromSuperview];
vc.view.frame = self.contentView.bounds;
[self.contentView addSubview:vc.view];
} completion:^(BOOL finished) {
[vc didMoveToParentViewController:self];
[self.currentViewController removeFromParentViewController];
self.currentViewController = vc;
}];
self.navigationItem.title = vc.title;
}
- (UIViewController *)viewControllerForSegmentIndex:(NSInteger)index {
UIViewController *vc;
switch (index) {
case 0:
vc = [self.storyboard instantiateViewControllerWithIdentifier:#"FooViewController"];
break;
case 1:
vc = [self.storyboard instantiateViewControllerWithIdentifier:#"BarViewController"];
break;
}
return vc;
}
I got this stuff from chapter 22 of Ray Wenderlichs book iOS5 by tutorial.
Unfortunately I don't have a public link to a tutorial. But there is a WWDC 2011 video titled "Implementing UIViewController Containment"
EDIT
self.typeSegmentedControl is outlet for your UISegmentedControl
self.contentView is outlet for your container view
self.currentViewController is just a property that we're using to store our currently used UIViewController
It's Matthias Bauch solution, but thought of sharing it in Swift anyway!
Edit:
Adding a link to a Swift 2.0 ready made demo app.
https://github.com/ahmed-abdurrahman/taby-segmented-control
var currentViewController: UIViewController?
#IBOutlet weak var contentView: UIView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBAction func switchHappeningTabs(sender: UISegmentedControl) {
if let vc = viewControllerForSelectedSegmentIndex(sender.selectedSegmentIndex) {
self.addChildViewController(vc)
self.transitionFromViewController(self.currentViewController!, toViewController: vc, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromRight, animations: {
self.currentViewController!.view.removeFromSuperview()
vc.view.frame = self.contentView.bounds
self.contentView.addSubview(vc.view)
}, completion: { finished in
vc.didMoveToParentViewController(self)
self.currentViewController!.removeFromParentViewController()
self.currentViewController = vc
}
)
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let vc = self.viewControllerForSelectedSegmentIndex(self.segmentedControl.selectedSegmentIndex) {
self.addChildViewController(vc)
self.contentView.addSubview(vc.view)
self.currentViewController = vc
}
}
func viewControllerForSelectedSegmentIndex(index: Int) -> UIViewController? {
var vc: UIViewController?
switch index {
case 0:
vc = self.storyboard?.instantiateViewControllerWithIdentifier("FooViewController") as? UIViewController
case 1:
vc = self.storyboard?.instantiateViewControllerWithIdentifier("BarViewController") as? UIViewController
default:
return nil
}
return vc
}
For someone want to implement the same in swift
import UIKit
class HomeController: UIViewController {
var currentViewController:UIViewController?
#IBOutlet weak var homeController: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let initialController:UIViewController = self.viewControllerForSegmentedIndex(0)
self.addChildViewController(initialController)
initialController.view.frame = self.homeController.bounds
self.homeController.addSubview(initialController.view)
self.currentViewController = initialController
}
#IBAction func segmentChanged(sender: UISegmentedControl) {
let viewCOntroller:UIViewController = viewControllerForSegmentedIndex(sender.selectedSegmentIndex)
self.addChildViewController(viewCOntroller)
self.transitionFromViewController(self.currentViewController!, toViewController: viewCOntroller, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromBottom, animations: {
self.currentViewController?.view.removeFromSuperview()
viewCOntroller.view.frame = self.homeController.bounds
self.homeController.addSubview(viewCOntroller.view)
}, completion:{ finished in
viewCOntroller.didMoveToParentViewController(self)
self.currentViewController?.removeFromParentViewController()
self.currentViewController = viewCOntroller
})
}
func viewControllerForSegmentedIndex(index:Int) -> UIViewController {
var viewController:UIViewController?
switch index {
case 0:
viewController = self.storyboard?.instantiateViewControllerWithIdentifier("StoryboardIdForFirstController")
break
case 1:
viewController = self.storyboard?.instantiateViewControllerWithIdentifier("StoryboardIdForSecondController")
break
case 2:
viewController = self.storyboard?.instantiateViewControllerWithIdentifier("StoryboardIdForThirdController")
break
default:
break
}
return viewController!
}
}
Storyboard view
A is root view controller, and B, C is sub view controller.
When you click segment, add sub view controller.
result
design
code
import UIKit
class SegmentViewController: UIViewController {
#IBOutlet weak var containerView: UIView!
var leftViewController: LeftViewController!
var rightViewController: RightViewController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let sb = storyboard {
leftViewController = sb.instantiateViewControllerWithIdentifier("leftViewController") as! LeftViewController
switchViewController(from: nil, to: leftViewController)
} else {
print("storyboard is nil")
}
}
func switchViewController(from fromVC: UIViewController?, to toVC: UIViewController?) {
if let from = fromVC {
from.willMoveToParentViewController(nil)
from.view.removeFromSuperview()
from.removeFromParentViewController()
} else {
print("fromVC is nil")
}
if let to = toVC {
self.addChildViewController(to)
to.view.frame = CGRectMake(0, 0, containerView.frame.width, containerView.frame.height)
self.containerView.insertSubview(to.view, atIndex: 0)
to.didMoveToParentViewController(self)
} else {
print("toVC is nil")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
removeViewController()
}
func removeViewController() {
if let leftVC = leftViewController {
if let _ = leftVC.parentViewController {
print("leftVC is using")
} else {
print("set leftVC = nil")
leftViewController = nil
}
}
if let rightVC = rightViewController {
if let _ = rightVC.parentViewController {
print("rightVC is using")
} else {
print("set rightVC = nil")
rightViewController = nil
}
}
}
#IBAction func onSegmentValueChanged(sender: UISegmentedControl) {
UIView.beginAnimations("xxx", context: nil)
UIView.setAnimationDuration(0.4)
UIView.setAnimationCurve(.EaseInOut)
switch sender.selectedSegmentIndex {
case 0:
UIView.setAnimationTransition(.FlipFromRight, forView: self.containerView, cache: true)
if let leftVC = leftViewController {
switchViewController(from: rightViewController, to: leftVC)
} else {
if let sb = storyboard {
leftViewController = sb.instantiateViewControllerWithIdentifier("leftViewController") as! LeftViewController
switchViewController(from: rightViewController, to: leftViewController)
} else {
print("storyboard is nil")
}
}
default:
UIView.setAnimationTransition(.FlipFromLeft, forView: self.containerView, cache: true)
if let rightVC = rightViewController {
switchViewController(from: leftViewController, to: rightVC)
} else {
if let sb = storyboard {
rightViewController = sb.instantiateViewControllerWithIdentifier("rightViewController") as! RightViewController
switchViewController(from: leftViewController, to: rightViewController)
} else {
print("storyboard is nil")
}
}
}
UIView.commitAnimations()
}
}
You could embed your initial view controller in a navigation controller. Do that by selecting the view controller in the storyboard, then Editor->Embed in->Navigation Controller.
In your indexDidChangeForSegmentedControl: method you simply push the corresponding view controller to the navigation stack:
- (IBAction)indexDidChangeForSegmentedControl:(UISegmentedControl*)segmentedControl
{
[self.navigationController pushViewController:[self.viewControllers objectAtIndex:[segmentedControl.selectedIndex]] animated:YES];
}
But your approach makes not too much sense at all when you are using storyboards.
I don't know whether you can wire up a single segmented control button to a view controller using segues. Just try it.
I ended up using a navigation controller to achieve a similar functionality.
import UIKit
class BaseViewController: UIViewController {
var currentSegmentIndex = 0
#IBOutlet weak var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl.selectedSegmentIndex = currentSegmentIndex
}
#IBAction func segmentedControlChanged(_ sender: Any) {
let idx = segmentedControl.selectedSegmentIndex
let storyboard = UIStoryboard(name: "Main", bundle: nil)
switch idx {
case 0:
let vc = storyboard.instantiateViewController(
withIdentifier: "Foo") as! FooViewController
vc.currentSegmentIndex = 0
navigationController?.viewControllers = [vc]
break
case 1:
let vc = storyboard.instantiateViewController(
withIdentifier: "Bar") as! BarViewController
vc.currentSegmentIndex = 1
navigationController?.viewControllers = [vc]
break
default:
break
}
}
}

Resources