UISplitViewController: How to prevent expansion when rotating from Compact to Regular - ios

There are many answers to the complementary question, which is how to prevent a transition to PrimaryOverLay on a from Regular to Compact interface change, eg use
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool
In my case, I have an iPhone 6+ with the detail view showing in portrait. When I rotate the device to horizontal (Compact to Regular), I want the primary view to stay hidden. I've tried setting the preferredDisplayMode to .PrimaryHidden in many places, but it has no apparent affect. Googling has turned up nothing.

Well, after I wrote the question, but before posting it, I tripped on a possible solution, which is to override the trait collection that the split view controller references.
I took that idea and decided to subclass UISplitViewController, and override the traitCollection property. That did the trick:
final class MySplitViewController: UISplitViewController {
var didOnce = false
override var traitCollection: UITraitCollection {
let old = super.traitCollection
let change = UITraitCollection(horizontalSizeClass: .Compact)
let new = UITraitCollection(traitsFromCollections: [old, change])
return new
}
Obviously this is hardcoded for one device - later I'll go and add some functions that I can use to control what is in fact returned.

Don't override traitCollection, instead use the method setOverrideTraitCollection:forChildViewController: in a parent view controller of your split controller, like in Apple's example AAPLTraitOverrideViewController.m
If your split controller doesn't have a parent, making a parent is really easy in the Storyboard. Add a new view controller, make it the entry point, add a container view, delete the default embedded view and instead add an embed segue to the split controller and set the override on self.childViewControllers.firstObject in viewDidLoad.

Related

Swift UISplitViewController - unable to present master view before detail view (iOS 14, Xcode 12.4)

I am having this issue where I am using a UISplitViewController MainSplitVC, and I am unable to present the master view controller over the detail view controller. Basically, when testing this on an iPad, I want the master and detail VC to be visible side by side, but on an iPhone (portrait mode), I want only the master VC. Currently, this works on iPad, but on an iPhone in portrait mode, Swift is showing the detail view controller first, and I have to click the back button in the navigation bar to return to the master view controller.
I have tried every possible approach that I could think of. For instance, I created a class for the Split View Controller, MainSplitVC, where I subclass UISplitViewController and UISplitViewControllerDelegate. Then, in viewDidLoad(), I set the preferred display mode to oneBesideSecondary (since allVisible was replaced by that according to Xcode). I also include the function collapseSecondary() to always collapse back to the master view controller.
class MainSplitVC: UISplitViewController, UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
print("viewDidLoad called")
self.preferredDisplayMode = UISplitViewController.DisplayMode.oneBesideSecondary
}
func splitViewController(
_ splitViewController: UISplitViewController,
collapseSecondary secondaryViewController: UIViewController,
onto primaryViewController: UIViewController) -> Bool {
print("collapseSecondary called")
return true
}
}
I have consulted many other posts regarding this issue, and all the posts indicate that using the collapseSecondary() function and setting preferredDisplayMode to oneBesideSecondary or allVisible should do the job. However, none of this is working. What's more is that the collapseSecondary() function is not even being called, even though I included UISplitViewControllerDelegate in the class header.
Could anyone clarify if I made any mistakes in the code below? When the app opens, I just want the master view controller to be shown; the detail view controller is simply a blank view controller that changes to another when something in the tableview of the master view controller is clicked.
The links I used for reference were as follows:
UISplitViewController showing detail view controller first on iPhone, also delegate not calling proper functions
UISplitViewController in portrait on iPhone shows detail VC instead of master
Open UISplitViewController to Master View rather than Detail
Thanks!
EDIT 2/3/21: I've resolved the issue. I instead extended SceneDelegate under UISplitViewControllerDelegate and included the following function:
func splitViewController(_ svc: UISplitViewController, topColumnForCollapsingToProposedTopColumn proposedTopColumn: UISplitViewController.Column) -> UISplitViewController.Column {
return .primary
}
The collapseSecondary function didn't work apparently because there is a bug where "Interface Builder doesn’t allow creating a classic style UISplitViewController. (65966010) (FB8107534)", so I get the error message "Skipping delegate callback, splitViewController:collapseSecondaryViewController:ontoPrimaryViewController:. Unsupported for UISplitViewController style DoubleColumn".
Thanks!
Returning .primary should solve your issue.
#available(iOS 14.0, *)
public func splitViewController(_ svc: UISplitViewController, topColumnForCollapsingToProposedTopColumn proposedTopColumn: UISplitViewController.Column) -> UISplitViewController.Column {
return .primary
}
[From Documentation]
Asks the delegate to provide the column to display after the split view interface collapses.
When the split view controller transitions from a horizontally regular to a horizontally compact size class, it calls this method and asks you for the column to display when that transition is complete. Use this method to customize the view controller you’re collapsing to.

Can't make custom segue in Xcode 10/iOS 12

I'm having the hardest time implementing a presentation of a drawer sliding partway up on the screen on iPhone.
EDIT: I've discovered that iOS is not respecting the .custom modalTransitionStyle I've set in the Segue. If I set that explicitly in prepareForSegue:, then it calls my delegate to get the UIPresentationController.
I have a custom Segue that is also a UIViewControllerTransitioningDelegate. In the perform() method, I set the destination transitioningDelegate to self:
self.destination.transitioningDelegate = self
and I either call super.perform() (if it’s a Present Modal or Present as Popover Segue), or self.source.present(self.destination, animated: true) (if it’s a Custom Segue, because calling super.perform() throws an exception).
The perform() and animationController(…) methods get called, but never presentationController(forPresented…).
Initially I tried making the Segue in the Storyboard "Present Modally" with my custom Segue class specified, but that kept removing the presenting view controller. I tried "Present as Popover," and I swear it worked once, in that it didn't remove the presenting view controller, but then on subsequent attempts it still did.
So I made it "Custom," and perform() is still being called with a _UIFullscreenPresentationController pre-set on the destination view controller, and my presentationController(forPresented…) method is never called.
Other solutions dealing with this issue always hinge on some mis-written signature for the method. This is mine, verbatim:
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
I've spent the last four days trying to figure out “proper” custom transitions, and it doesn't help that things don’t seem to behave as advertised. What am I missing?
Instead of using a custom presentation segue, you could use a Container View for your drawer. This way, you can use a UIViewController for your Drawer content, while avoiding the issue with the custom segue.
You achieve this in two steps:
First pull a Container View into your main view controller and layout it properly. The storyboard would look like this: (You can see you have two view controllers. One for the main view and one for the drawer)
Second, you create an action that animates the drawer in and out as needed. One simple example could look like this:
#IBAction func toggleDrawer(_ sender: Any) {
let newHeight: CGFloat
if drawerHeightConstraint.constant > 0 {
newHeight = 0
} else {
newHeight = 200
}
UIView.animate(withDuration: 1) {
self.drawerHeightConstraint.constant = newHeight
self.view.layoutIfNeeded()
}
}
Here, I simply change the height constraint of the drawer, to slide it in and out. Of course you could do something more fancy :)
You can find a demo project here.

UISplitViewController: How to force showing the master ViewController

I am using a UISplitViewController, with the master and the detail viewcontrollers, without UINavigationControllers.
In some cases (for example when clicking on a universal link), I would like to force the app to always show the master viewcontroller.
How can I do that?
Is there a way to switch back from detail to master programmatically?
The split view controller is a beast, and the documentation is confusing. It is best understood by considering it as operating in two different modes: collapsed or not. Collapsed mode applies when the split view is presented in a horizontally compact view (i.e. iPhone), otherwise it is not collapsed (i.e. iPad).
The property preferredDisplayMode only applies if the view is NOT collapsed (i.e. iPad), and you can use this to select the master or detail view.
In collapsed mode, unless you are using navigation controllers, the original master view may be discarded:
After it has been collapsed, the split view controller reports having
only one child view controller in its viewControllers property. The
other view controller is collapsed into the other view controller’s
content with the help of the delegate object or discarded temporarily
But it is much better to use navigation controllers, as the split view controller is designed to work in conjunction with them:
The split view controller knows how to adjust the interface in more
intuitive ways. It even works with other container view controllers
(like navigation controllers) to present view controllers.
If you are using navigation controllers then the original master view may be at the bottom of the navigation stack:
In a horizontally compact environment, the split view controller acts
more like a navigation controller, displaying the primary view
controller initially and pushing or popping the secondary view
controller as needed
So you can do something like this:
if split.isCollapsed,
let nav = split.viewControllers[0] as? UINavigationController
{
nav.popToRootViewController(animated:false)
} else {
split.preferredDisplayMode = .allVisible
}
(It can get even more complicated if your master view pushes views in master as well as showing detail views. This code will pop to the root of the master view navigation stack)
You can set the preferredDisplayMode
self.splitViewController?.preferredDisplayMode = UISplitViewControllerDisplayMode.allVisible
Or if you are looking for something like a toggle action:
extension UISplitViewController {
func toggleMasterView() {
let barButtonItem = self.displayModeButtonItem
UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: nil, for: nil)
}
}
Usage:
self.splitViewController?.toggleMasterView()
You can define a custom UISplitViewController and assign it to your split view in storyboard:
import UIKit
class GlobalSplitViewController: UISplitViewController, UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return true
}
}
My solution is to swap the position of your primary and secondary ViewControllers if user is using an iPad. Then set preferredDisplayMode = .primaryHidden. Example code below.
splitViewVieController = UISplitViewController()
let isIphone = UIDevice.current.userInterfaceIdiom == .phone
splitViewVieController.viewControllers = isIphone ? [primaryNavController, seconaryNavController] : [seconaryNavController, primaryNavController]
splitViewVieController.preferredDisplayMode = .primaryHidden
We can change the position or width of the primary ViewController if needed.
splitViewVieController.maximumPrimaryColumnWidth = splitViewVieController.view.bounds.width
splitViewVieController.preferredPrimaryColumnWidthFraction = 0.5
splitViewVieController.primaryEdge = .trailing

Restricting portrait orientation to collectionview in iOS doesn't seem to work

I have multiple viewControllers in my app and I would like to restrict certain views only to portrait orientation. I have achieved this by overriding shouldAutoRotate and supportedInterfaceOrientations like below
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientation.Portrait.rawValue)
}
I have followed the same for a UICollectionView but it doesn't seem to work. I would like to know if this is the right way to achieve it. Help on this would be much appreciated. Thanks in advance!
In iOS 8 or later, if you want to control the allowed orientations per view controller:
Make sure the "Supported interface orientations" in the Info.plist allows all orientations you want the app to be able to use. (Or just check the correct "Device Orientations" in the Xcode UI interface to the Info.plistfile)
Per view controller, implement (example restricting to portrait):
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
A problem you can run in to is if your view controller is embedded in another view controller (like an UINavigationController or a UITabBarController, or both).
I suspect this is the situation you are describing.
If so, all view controllers involved need to implement the supportedInterfaceOrientations() method. AFAIK, if you for example have a UINavigationController above your view controller, you need to sub class and create your own navigation controller with the method implemented.

How I can create an UIPageViewController where are all screens different and has own ViewControllers?

I want to use the cool swipe animation between screens - UIPageViewController (yes, you know the style from the intro screen), but all the code I found on the Internet and Github was useless for me.
I found demos with just one UIViewController in the Storyboard interface and almost all the apps showed how to change an image source from an array. I read the Apple reference, but I do not understand it.
I need a few ViewControllers on my Storyboard (I want to design all the screens in the UIPageViewController differently, they will be connected to own ViewControllers classes) who will be presented in the UIPageViewController.
Or of course if you know a better way how do that please say so! But I need the feature that if you swipe, the screen moves with you.
Does someone know how to do that?
There's nothing in UIPageViewController that requires the various view controllers to be same class. So, just implement viewControllerBeforeViewController and viewControllerAfterViewController that return different types of view controllers. If you want to reference child view controllers from the storyboard, just give those scenes unique storyboard ids, and then you can use instantiateViewControllerWithIdentifier. You might, for example, have an array of storyboard identifiers, and use that to determine which type of scene is "before" and "after" the current one.
There are tons of ways of implementing this, but you could do something like:
class ViewController: UIPageViewController, UIPageViewControllerDataSource {
let identifiers = ["A", "B", "C", "D"] // the storyboard ids for the four child view controllers
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
setViewControllers([viewControllerForPage(0)!], direction: .Forward, animated: false, completion: nil)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var page = (viewController as PageDelegate).pageNumber + 1
return viewControllerForPage(page)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var page = (viewController as PageDelegate).pageNumber - 1
return viewControllerForPage(page)
}
func viewControllerForPage(page: Int) -> UIViewController? {
if page >= 0 && page < identifiers.count {
let controller = storyboard?.instantiateViewControllerWithIdentifier(identifiers[page]) as? UIViewController
(controller as PageDelegate).pageNumber = page
return controller
}
return nil
}
}
Clearly, if you wanted to be more elegant here, you could maintain a cache of previously instantiated view controllers, but make sure you respond to memory pressure and purge that cache if necessary. But hopefully this illustrates the fact that there's nothing about page view controllers that dictates that the children are a particular class of controller.
By the way, the above assumes that each of the child view controllers conforms to a protocol to keep track of the page number.
/// Page delegate protocol
///
/// This is a protocol implemented by all of the child view controllers. I'm using it
/// just to keep track of the page number. In practical usage, you might also pass a
/// reference to a model object, too.
#objc protocol PageDelegate {
var pageNumber: Int { get set }
}
If you want to go a completely different direction, another approach is to use standard storyboard where you have segues that present one view controller after another, and then for each view controller implement swipe gesture recognizers, where swiping from the right performs the segue to transition to the next scene (e.g. an IBAction that does performSegueWithIdentifier), and another swipe gesture recognizer (left to right) will dismiss the view controller.
Finally, if you want these gesture recognizers to be interactive (e.g. to follow along with the user's finger), you could use custom transitions, combined with interactive transitions. For more information, see WWDC 2013 video Custom Transitions Using View Controllers or WWDC 2014 videos View Controller Advancements in iOS 8 (which, about 20 minutes into the video, describes how custom transitions have been enhanced in iOS 8 with presentation controllers) and A Look Inside Presentation Controllers.
I think you might take advantage of View Controller Containment.
We are dealing with 4 elements at play here.
Main View Controller
scroll view
UIPage control
Detail View Controllers
You would add the scroll view and the page control as the main view controller's properties. The main controller would handle the scrolling logic, basically syncing the horizontal scrolling between the scrollview and the page control.
The contents of the scroll view would be constituted by root views of all the detail view controllers.

Resources