I'm implementing the iOS 14 (iPadOS 14) sidebar (UISplitViewController with TripleColumn) and having strange "sidebar toggle icon" behavior.
In iOS 13 I'm using the tab bar with some split views and table views so I need the Triple Column instead of the Double Column to work.
For example, using the sidebar in "flights" tab needs three columns:
And there are some tabs with only one column (in iOS 13, it was a table view instead of a split view). I set the supplementary view to nil, and hide the view by calling "hide" method implemented in iOS 14. (See below for code):
The "sidebar toggle icon" on the upper left is automatically displayed. After clicking the toggle icon, the sidebar hides correctly but an "back button" was created on my secondary view(a UITableViewController embedded in a UINavigationController):
Pressing (clicking) the back button has no response. User can still swipe from the left edge of the screen to make sidebar reappear but the "back button" is confusing. My expected behavior is, after the toggle icon selected in sidebar, display the "sidebar toggle icon" instead of the "back button" in the secondary view. And after pressing the "sidebar toggle icon" in secondary view, the sidebar reappears.
Like the Photos app in iOS 14 (iPadOS 14), the toggle button is shown instead of the back button. And clicking the toggle icon will make the sidebar shown again. (but it's a double column split view)
My code:
SceneDelegate.swift:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
if #available(iOS 14.0, *) {
let main = UIStoryboard(name: "Main", bundle: nil)
let splitViewController = UISplitViewController(style: .tripleColumn)
splitViewController.preferredDisplayMode = .twoBesideSecondary
splitViewController.preferredSplitBehavior = .tile
splitViewController.setViewController(SideBarViewController(), for: .primary)
// fall back for compact screen
splitViewController.setViewController(main.instantiateInitialViewController(), for: .compact)
window.rootViewController = splitViewController
self.window = window
window.makeKeyAndVisible()
}
}
}
SideBarViewController:
// if the first tab (dashboard) was selected
private func selectDashboardTab() {
if #available(iOS 14.0, *) {
let dashboardVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DashboardTab") as? UINavigationController
splitViewController?.preferredPrimaryColumnWidth = 250.0
splitViewController?.preferredDisplayMode = .twoBesideSecondary
splitViewController?.preferredSplitBehavior = .tile
splitViewController?.setViewController(dashboardVC, for: .secondary)
splitViewController?.setViewController(nil, for: .supplementary)
splitViewController?.hide(.supplementary)
}
}
I was able to reproduce the problem... but was unable to circumvent it using the available API. Apple stubbornly decided that the sidebar icon would always be in the supplementary controller when in a 3-column layout, it seems.
That being said, I've coded a hack to fix it. I managed to create a UISplitViewController subclass that "fakes" an editable style property, thus allowing us to set the number of columns (the hack just creates a brand new controller and makes it the new rootViewController).
The hack allows us to switch between 2-colulm and 3-column layout at will, and seems to solve the sidebar icon problem.
Link to the Xcode project below. But here's the gist of it:
class AdaptableSplitViewController: UISplitViewController {
override var style: Style {
get {
super.style
}
set {
guard newValue != style else { return }
let primaryController = viewController(for: .primary)
let supplementaryController = viewController(for: .supplementary)
let secondaryController = viewController(for: .secondary)
let newSplitController = AdaptableSplitViewController(style: newValue)
newSplitController.setViewController(primaryController , for: .primary)
newSplitController.setViewController(secondaryController, for: .secondary)
if newValue == .tripleColumn {
newSplitController.setViewController(supplementaryController, for: .supplementary)
}
UIApplication.shared.windows[0].rootViewController = newSplitController
}
}
}
Let me know if this helps.
Link to the zipped Xcode sample project
Late in the discussion but... I've encountered a similar behavior.
Just before setting you secondary, set it to nil. Strange, I know, but it fixed it for me. Like this:
splitViewController?.setViewController(nil , for: .secondary)
splitViewController?.setViewController(dashboardVC, for: .secondary)
Related
there π
I know hide title bar in Storyboard.
But I can't find the way in SwiftUI.
I want to hide title bar with control buttons and make floating image view.
Let me know please.
If you know related example, tell me please.
My little english sorry.. π
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}.windowStyle(HiddenTitleBarWindowStyle())
}
}
try HiddenTitleBarWindowStyle()
Removing the Title Bar in Your Mac App Built with Mac Catalyst
Display content that fills the entire height of a window by removing the title bar.
By default, Mac apps built with Mac Catalyst display a title bar across the top of their windows. A horizontal line separates the title bar from the content of the window.
Some Mac apps such as Messages and Contacts have no title bar in their main window. Instead, the top of the window shows only the Close, Minimize, and Zoom buttons with no separator between them and the window's content. In this UI design, the content area fills the entire height of the window.
The following image illustrates these styles in two windows. The first window displays a title bar, while the second has none.
Screenshot of two windows, one stacked above the other, with a dark background in the content area of each window.
Remove the Title Bar
If you choose to design your window without a title bar, you must remove it from the window. To remove the title bar, set the title barβs titleVisibility property to UITitlebarTitleVisibility.hidden and the toolbar property to nil. The following code shows how to remove the title bar and its separator from the window during the setup of a new scene.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
#if targetEnvironment(macCatalyst)
if let titlebar = windowScene.titlebar {
titlebar.titleVisibility = .hidden
titlebar.toolbar = nil
}
#endif
}
Click here for more information
I could not find a way to hide the toolbar entirely in SwiftUI. But this is a possible workaround. You can put this code in your AppDelegate file.
func applicationDidFinishLaunching(_ aNotification: Notification) {
let window = NSApplication.shared.windows.first!
window.titlebarAppearsTransparent = true
window.backgroundColor = .white
window.standardWindowButton(.closeButton)!.isHidden = true
window.standardWindowButton(.miniaturizeButton)!.isHidden = true
window.standardWindowButton(.zoomButton)!.isHidden = true
}
Using this code will make it appear that the toolbar is hidden when in reality, it is still there. But the buttons are hidden, and the background is transparent.
First of all the native macOS application is made into an accessory type application 3 seconds after launching (to show an info screen first, before the app goes into the system menu bar):
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
NSApplication.shared.setActivationPolicy(.accessory)
}
It has a status bar menu created with:
class func createMenu(color: Bool) -> Void {
let statusBar = NSStatusBar.system
self.sharedInstance.storedStatusItem = statusBar.statusItem(withLength: NSStatusItem.variableLength)
self.sharedInstance.storedStatusItem.menu = ABCMenu.statusBarMenu()
}
The user has several options in the status bar menu to open different screens with controls. One of them is shown with:
class func showServiceViewController() -> Void {
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: Bundle.main)
guard let vc = storyboard.instantiateController(withIdentifier: "ABCServiceViewController") as? ABCServiceViewController, let checkedWindow = ABCUIManager.sharedInstance.window else {
return
}
checkedWindow.contentViewController = vc
checkedWindow.setIsVisible(true)
checkedWindow.orderFrontRegardless()
}
The problem is that sometimes the selected view controller is not brought to the background and has to be found underneath many other already opened applications and windows. Most of the time it works fine, but not always.
Are there any better ways to assure that the new view controller is always brought up to the highest level and shown to the user?
Thank you for any suggestions.
I would activate application before showing window (as you have accessory application it is not activated by default and must be done programmatically)
...
NSApplication.shared.activate(ignoringOtherApps: true)
checkedWindow.contentViewController = vc
checkedWindow.setIsVisible(true)
checkedWindow.orderFrontRegardless()
}
I have a toolbar that's instantiated on viewDidLoad on top of a webkit. When I take a snapshot on the simulator, the toolbar is missing which is what I would like. When built on the device, the toolbar is there.
I tried to hide the toolbar with:
toolbar.isHidden = true
but the application crashes with toolbar being nil. If I change it to:
toolbar?.isHidden = true
It still shows up considering it still thinks it's nil.
The toolbar is set up on viewDidLoad by calling another function:
var toolbar : UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
setUpToolBar()
}
func setUpToolBar() {
let saveButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(takeScreenshot))
...
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 300, width: 200, height: 50))
toolbar.setItems([saveButton,flexibleSpaceFillerLeft,userAgentButton,flexibleSpaceFillerRight,doneButton], animated: true)
view.addSubview(toolbar)
}
The code for my snapshot is below. This is where I tried to hide the toolbar before taking the snapshot.
#objc func takeScreenshot() {
webView.takeSnapshot(with: nil, completionHandler: { (image,error) in
if let image = image {
self.screenshotOfWindow = image
self.showScreenshotEffect()
self.saveAllData()
} else {
print (error?.localizedDescription as Any)
}
})
}
Here's the screen I need to take a screenshot of:
The red box in the screenshot is the bar that I need to disappear from the screenshot.
I'd like to be able to take the screenshot without the bottom bar in view. As stated before, this works in the simulator, but the device always shows the bar. There's also a "navigation controller" gap at the top of the screenshot since the top bar covers part of the screen at top, but this is just blank and something I can address later.
I just wanted to come back and answer how I solved this. The webview is embedded in a navigation controller, but I was creating the toolbar programmatically on viewDidLoad by calling a setupToolBar function I had created early on in the project. I could hide the toolbar, but it was still being captured while taking the screenshot. I commented all of that code out and used the navigation controller's toolbar instead. Now when I take the screenshot, the bottom and top bar of the navigation controller is not part of the screenshot.
I have set auto-layout for the label so it should be centered right above my button, however when I click on the button the label goes up in the left corner. I'm a totally new beginner to coding, so bare in mind I might have just missed something very simple? I would guess in my code I need some kind of way to tell the position of the label to be after the click?
This is my code for the button action:
nextStagetwo.textAlignment = NSTextAlignment.Center
nextStagetwo.userInteractionEnabled = true
nextStagetwo.text = "Go to next stage"
self.view.addSubview(nextStagetwo)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
nextStagetwo.addGestureRecognizer(gestureRecognizer)
}
}
func handleTap(gestureRecognizer: UIGestureRecognizer) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc: AnyObject! = storyboard.instantiateViewControllerWithIdentifier("stagethree")
self.presentViewController(vc as! UIViewController, animated: true, completion: nil)
}
Run your application in Xcode 7 and select the debugger view and then the debugger toolbar button with tooltip, "Debug View Hierarchy" (third button from right in the debugger toolbar). That will show you what auto layout is computing for each item on the screen. You can peel off layers as needed in this view. Compare those values with your auto layout constraints for that item and its containers.
Also, make sure you don't have any auto layout warnings in the Xcode Interface Builder for your storyboard.
I added this to the code, which was what was missing in my code:
let nextStagetwo = UILabel(frame: CGRectMake(250, 250, 250, 250))
nextStagetwo.center = CGPointMake(210, 200)
At the moment I have a standard tab bar, when tapped goes to its corresponding viewController. But I want to make a menu pop out from tab bar when more tab is selected, as shown in below image.
Is any suggestion to implement this?
Thanks in advance.
I would recommend you do so:
First, you should think of all the tab types that could be in tab bar. On your screenshot there are tabs, that present controller, and tab, that presents menu. So we could create enum with all these types:
enum TabType {
case controller
case menu
}
After that you can store array of tab types in order they are shown in tab bar, for your screenshot like so
let tabTypes: [TabType] = [.controller, .controller, .controller, .controller, .menu]
Then you should implement UITabBarControllerDelegate's func tabBarController(_:, shouldSelect:) -> Bool method, which returns true if tab bar is allowed to select the passed controller, and false otherwise.
If you return true than all other work (like presenting view controller and other stuff) tab bar controller will do for you.
In your case you want to execute custom action on tab click, so you should return false. Before returning you should present your menu.
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if let index = tabBarController.viewControllers?.index(of: viewController),
index < tabBarTypes.count {
let type = tabBarTypes[index]
switch type {
case .menu:
// perform your menu presenting here
return false
case .controller:
// do nothing, just return true, tab bar will do all work for you
return true
}
}
return true
}
In this implementation you can easily change tab types order or add some another tab type and handle it appropriate.
Its not good UI but although if you want.
First You have to implement delegate method of UITabbarControllerDelegate as below
func tabBarController(_ tabBarController: UITabBarController, shouldSelect
viewController: UIViewController) -> Bool {
if viewController.classForCoder == moreViewController.self
{
let popvc = MoreSubMenuViews(nibName: "MoreSubMenuViews", bundle: Bundle.main)
self.addChildViewController(popvc)
let tabbarHeight = tabBar.frame.height
let estimatedWidth:CGFloat = 200.0
let estimatedHeight:CGFloat = 300.0
popvc.view.frame = CGRect(x:self.view.frame.width - estimatedWidth, y: self.view.frame.height - estimatedHeight - tabbarHeight, width: estimatedWidth, height: estimatedHeight)
self.view.addSubview(popvc.view)
popvc.didMove(toParentViewController: self)
print("sorry stop here")
return true // if you want not to select return false here
}else{
//remove popup logic here if opened
return true
}
}
Here moreViewController is last tab controller & MoreSubMenuViews is nib/xib file which contains buttons shown in you image.
Instead of showing a menu, you could use a scrollable tabs view for a better UI. If you prefer using a library, here's a simple scrollable tab-bar you could implement.
This is an abuse of the UI patterns layout in Apples HIG. Specifically:
Use a tab bar strictly for navigation. Tab bar buttons should not be used to perform actions. If you need to provide controls that act on elements in the current view, use a toolbar instead.
This control should be used to flatten your app hierarchy. It seems that in this case you are mixing functionality of the button. Sometimes it selects a separate view controller, sometimes it displays a action list. This is a confusing situation for users and should be avoided.
A way you could achieve this and still adhere to HIG is by using navigation or tool bars. Imbed this control in a toolbar button. The most simple case would be to invoke a UIActionController with the .actionSheet style selected.
As per my understanding what you want is that, tab 1 is selected and user goes to tab 5 then background will be tab 1 & vice-versa for tab 2,3 & 4 and there should be pop up like buttons as shown in your image. please correct me if I'm wrong.
For this you have to capture the image while user navigate through tabs.
Please find below code in AppDelegate,
var currentImage: UIImage! //It will be public variable
Tabbar delegate methods,
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.selectedIndex == 4 {
let moreVC = tabBarController.selectedViewController as! MoreVC
moreVC.currentImage = currentImage
}
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if tabBarController.selectedIndex != 4 {
let navController = tabBarController.selectedViewController as! UINavigationController
let viewController = navController.viewControllers.last
currentImage = Common.imageWithView(inView: (viewController?.navigationController?.view)!) //UIImage(view: (viewController?.navigationController?.view)!)
}
return true
}
Here I've taken static 4 as last tab index & MoreVC will be the associated ViewController of tab index 4.
Common class to get image from view,
class Common {
static func imageWithView(inView: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(inView.bounds.size, inView.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
inView.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
}
Please find MoreVC,
#IBOutlet weak var imageView: UIImageView!
var currentImage: UIImage! {
didSet {
imageView.image = currentImage
}
}
Please find below image for MoreVC Storyboard. Look it does not contain NavigationController like all other ViewControllers.
Let me know in case of any queries.
1)
Create a "Tab5ViewController" and use this:
static func takeScreenshot(bottomPadding padding: CGFloat = 0) -> UIImage? {
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: layer.frame.size.width, height: layer.frame.size.height - padding), false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
Use the screenshot as a background image for your "Tab5ViewController"
2) In your "Tab5ViewController" you can have the stack component (the additional tabs) and then just add/remove child view controllers based on the selection
3)
fix edge cases (like tab selection highlight and so on...)