In iOS 14, the new split view controller handles the bar button items for you. That's cool! So in portrait we see this:
We're in portrait, so that button at the top left summons the "overlay" version of the Primary column.
And in landscape we see this:
We're in landscape, so that button at the top left hides or shows the "side by side" version of the Primary column.
Now I want to know how to control the presence of these buttons individually. I see that I can set presentsWithGesture to false to hide both buttons, but that's not what I want. My question is: how can I hide the second button (landscape) but not the first button (portrait)?
Set a delegate on the split view controller and implement this delegate method:
func splitViewController(_ svc: UISplitViewController, willChangeTo displayMode: UISplitViewController.DisplayMode) {
svc.presentsWithGesture = displayMode != .oneBesideSecondary
}
In SwiftUI, this solution works – tested on iOS 16!
extension UISplitViewController {
open override func viewDidLoad() {
preferredDisplayMode = UISplitViewController.DisplayMode.oneBesideSecondary
// remove sidebar button, make sidebar always appear !
presentsWithGesture = displayMode != .oneBesideSecondary
}
}
Related
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.
For my app, I have created a split view embedded in a container view, i.e. the split view is not at the root of the application.
As can be seen in the image, I added a navigation item to the master view that serves as a back button and pops the entire split view off the main navigation stack.
#IBAction func backButtonTapped(_ sender: UIBarButtonItem) {
parent?.navigationController?.popViewController(animated: true)
}
This is working well on all devices when I set the split view's display mode to allVisible. It works both for the collapsed view (e.g. on iPhone portrait mode) and the expanded split view.
Problem: When I use another display mode such as Auto or primaryHidden the navigation button in the master view still shows but does not work in landscape (expanded) view. The button handler is called but above statement does not navigate away from the split view. The parent's navigation controller does not seem to be accessible this way (= nil). Why doesn't the statement work in some display modes, and how can I make it work?
This feels a bit clumsy, but it does the job. A better solution may come from understanding why the parent navigation controller is accessible in some display mode but not in others.
What does work is going via the detail view's navigation controller and removing that from the stack. The display mode is changed here to prevent some ugly transition effect.
#IBAction func backButtonTapped(_ sender: UIBarButtonItem) {
if (splitViewController!.viewControllers.count > 1) {
// master and detail visible in split view
let detailViewController = splitViewController!.viewControllers[1]
splitViewController!.preferredDisplayMode = .primaryHidden
detailViewController.navigationController?.popViewController(animated: true)
} else {
// split view collapsed into single view mode (e.g. iPhone portrait)
parent?.navigationController?.popViewController(animated: true)
}
}
I am pretty much trying to replicate the same tabBar popup as you see in the yelp app (before and after screenshots at the bottom) where no matter what view your in you can press on the center tabBar item and pop up will appear.
Coincidentally I have 5 tabBar items (like Yelp) and I am trying to have three popups with a image and title for each (like Yelp). Seeing that what I am trying to do is already done in an app shows me that this is possible, but I do not know how to do it. I have tried to change the types of relationships between view controllers or do it programmatically, but nothing seems to work. What am I missing or doing wrong?
Tabbar Controller Code:
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController.tabBarItem.tag == 1 {
return false
} else {
return true
}
}
Before Press
After Press
One solution could be to adopt the UITabBarControllerDelegate.
This way we can use the func tabBarController(UITabBarController, didSelect: UIViewController) method of the delegate to alter the regular presentation behavior and show our popups instead. We could find the offset required (in terms of CGPoint) relative to the tab bar button and then apply that offset and add the popup buttons to as a subview. Note that for this method you would need to programmatically set the frames of your popup buttons.
Alternatively, you could also make a bunch of popup buttons and set their alphas to zero and one when clicked. Hope this helped! Thanks :)
Custom action for tab bar
UITabBarControllerDelegate documentation
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
I'm working on Apple TV project. The project contains tab bar view controller, normally the tab bar will be appeared when swiping up on remote and hidden when swiping down. But now I reverse that behavior and I want to force focus another view when swiping up(normally focus on tab bar). Any way to do that? Thank you.
In your UIViewController, override shouldUpdateFocusInContext. If you detect an upward navigation into the tab bar, return false to prevent focus from reaching the tab bar. Then use a combination of preferredFocusEnvironments + setNeedsFocusUpdate to redirect focus somewhere else:
override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
if let nextView: UIView = context.nextFocusedView{
if ( context.focusHeading == .up && nextView.isDescendant(of: tabBar) ){
changeFocusTo(myView)
return false
}
}
}
internal var viewToFocus: UIView?
func changeFocusTo(_ view:UIView? ){
viewToFocus = view
setNeedsFocusUpdate()
}
override var preferredFocusEnvironments: [UIFocusEnvironment]{
return viewToFocus != nil ? [viewToFocus!] : super.preferredFocusEnvironments
}
This is a generally useful technique for customizing focus updates. An alternative technique is to use UIFocusGuide. You could insert a focus guide underneath the tab bar or surround the tab bar with a focus guide to redirect focus. Though focus guides are useful for simple cases, I have generally had better results using the technique I am describing instead.
I got the same issue with focus of UITabbarController before and I found the solution in Apple Support
Because UIViewController conforms to UIFocusEnvironment, custom view
controllers in your app can override UIFocusEnvironment delegate
methods to achieve custom focus behaviors. Custom view controllers
can:
Override the preferredFocusedView to specify where focus should start
by default. Override shouldUpdateFocusInContext: to define where focus
is allowed to move. Override
didUpdateFocusInContext:withAnimationCoordinator: to respond to focus
updates when they occur and update your app’s internal state. Your
view controllers can also request that the focus engine reset focus to
the current preferredFocusedView by callingsetNeedsFocusUpdate. Note
that calling setNeedsFocusUpdate only has an effect if the view
controller contains the currently focused view.
For more detail, please check this link
https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html#//apple_ref/doc/uid/TP40015241-CH5-SW14