UiSegmentedControl on NavigationBar below Title - ios

I am new on iOS Development and during my works for an app I am building right now some doubts have appeared to me. I am trying to build a Screen that will be compounded by multiple ViewControllers, but on the NavigationBar I would like to have a UiSegmentedControl above the Title, something like a Scope Bar to control the navigation between the children ViewController. I wanted to build something similar to what we have on HealthKit Dashboard:
.
What kind of approach do you suggest to do that? I understand that some questions have already been done about it, but after a long research I have not got to a conclusion.
During my research I noticed that a UISearchBar on the NavigationBar ( to build the Scope Bar ) is only possible for UITableViewControllers, Am I right? So I think that can not be an approach.
My next idea was to use a UISegmentedControl placed manually below the NavigationBar and then use the Containment Api to change to the different ViewControllers for this Screen. The problem here, is I will have to duplicate the UISegmentedControl on all children ViewControllers. Is there any way to not have to duplicate that?
Another approach I tried was doing my own titleView for the NavigationBar with a NavigationBar and a UISegmentedControl below. I don’t like this idea, neither it went well trying to replicate the NavigationBar.
Finally, another approach I thought was using a UIPageViewController. Although this approach sounds a good idea to me, I think I will also have to duplicate the UISegmentedControl.
In the end I think the best solution is to have a UISegmentControl on the NavigationBar, but I am not seeing how to implement this.
What do you think is the best approach to accomplish my ideia? I thought that it would be easy because it is a pattern I see in many apps. Any suggestions?
I am doing this on XCode 6.1.1 using Swift for iOS 8.
Thanks a lot for your help.

You can get this effect by adding the segment as the title view and setting your desired prompt. In interface builder it looks like this:

Add a UIToolbar to your view. Doesn't matter if you add it through code or interface builder. Then you add your UISegmentedControl as custom view of an UIBarButtonItem
let toolbar = UIToolbar()
toolbar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(toolbar)
NSLayoutConstraint.activate([
toolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
// Add SegmentedControl like this:
toolbar.setItems([UIBarButtonItem(customView: mySegmentedControl)], animated: false)
toolbar.delegate = self
Then implement this delegate method (See documentation for UIBarPosition.topAttached)
extension MyViewController: UIToolbarDelegate {
public func position(for bar: UIBarPositioning) -> UIBarPosition {
.topAttached
}
}
Then you have what you need. But there's still a separator line between the navigation bar and the toolbar. To get rid of it use this extension methods and call them in viewWillAppear and viewWillDisappear:
extension UINavigationBar {
func hideHairline() {
// Hide border line of navigation bar since we're showing a toolbar
if #available(iOS 13.0, *) {
standardAppearance.shadowColor = nil
standardAppearance.shadowImage = nil
} else {
shadowImage = UIImage()
setBackgroundImage(UIImage(), for: .default)
}
}
func restoreHairline() {
// Hide border line of navigation bar since we're showing a toolbar
if #available(iOS 13.0, *) {
standardAppearance.shadowColor = .separator
} else {
shadowImage = nil
setBackgroundImage(nil, for: .default)
}
}
}

Related

iOS 11 UINavigationBar Transparency in pushed ViewController

I've been trying to implement Apple Music like transparent navigation bar for pushed view controller. There are a lot of solutions on Internet saying place the code below into viewDidLoad:
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
But the thing is that it only works for root controller, e.g. UITableViewController with a list of items. When I tap on an item and open it's details I expect to see transparent navigation bar, but after appearing it becomes solid (not even translucent). Even setting barTintColor does not help.
What am i doing wrong? Or is it a known issue in iOS 11? It used to work before...
I confirm that transparent navigation bar is not working in iOS 11 for pushed viewcontroller, instead just appears black without translucent #screenshot.
Firstly, I have filed this bug report, lastly :) I found a quick workaround that presenting and dismissing a UIViewcontroller fixes this issue, as following:
if (self.navigationController!.viewControllers.count > 1) {
if #available(iOS 11.0, *) {
self.present(UIViewController(), animated: true, completion: {
self.dismiss(animated: false)
})
self.scrollView.contentInsetAdjustmentBehavior = .never
} else {
self.automaticallyAdjustsScrollViewInsets = false
}
self.extendedLayoutIncludesOpaqueBars = false
}
I am using above code in viewWillAppear and my UI is being generated programatically without storyboard or xib, so it works seamlessly :) and glad I get expected result #screenshot

UISearchBarController iOS 11 issue - SearchBar and scope buttons overlap

Referred here and here. No answer in first link. In the second link, though the answer is not accepted, but the link to apple developer forum gives error.
Before iOS 11 :
iOS 11 :
Note : Same device same code.
Also, this would mean, all apps using this feature have to be republished ?
Adding these lines fixed it for me:
override func viewDidLayoutSubviews() {
self.searchController.searchBar.sizeToFit()
}
I can get the initial appearance to display correctly in iOS11 using the following code (as per greg's answer):
[self.searchController.searchBar sizeToFit];
if (#available(iOS 11.0, *)) {
self.navigationItem.searchController = self.searchController;
self.navigationItem.hidesSearchBarWhenScrolling = NO;
} else {
// Fallback on earlier versions
self.tableView.tableHeaderView = self.searchController.searchBar;
}
However, if the app is backgrounded then restored while the search bar was active, the appearance would end up overlapped as shown in Nitish's second screenshot above.
I was able to fix that with the following workaround:
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
self.searchController.searchBar.showsScopeBar = NO;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.showsScopeBar = YES;
[self.searchController.searchBar sizeToFit];
}];
(I'm still working on how to workaround the layout issues following an interface orientation change while the search bar is active - that still ends up overlapped.)
In the radar that Ray Wenderlich filed, #benck posted this answer from WWDC, which, if I'm not mistaken, hasn't been posted yet.
Per your comments, your UISearchController's UISearchBar has been assigned to your UITableView's tableHeaderView. In iOS 11, you should instead be assigning your UISearchController to the searchController property of your view's navigationItem. You no longer need to assign the UISearchBar anywhere. See Apple's documentation on this new property.
I met the same issue on my app, my solution is in iOS 11, using apple suggested new way for searchBar which is in navigationItem, otherwise, using the old way. My code in viewDidLoad() as below:
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchViewHeight.constant = 0
} else {
searchView.addSubview(searchController.searchBar)
}
I have two IBOutlets: searchView and searchViewHeight:
#IBOutlet var searchView: UIView!
#IBOutlet var searchViewHeight: NSLayoutConstraint! // new added for iOS 11
Before iOS 11, my viewController's hierarchy as below:
I have a searchView which height is 44 to contains my searchController's searchBar view. It's under navigation bar.
In iOS 11, I add a new IBOutlet for searchView's height constraint, and set its constant to 0, hide this container view. And add searchController as a part of navigation item.
See apple's document:
https://developer.apple.com/documentation/uikit/uinavigationitem/2897305-searchcontroller
One more thing is under iOS 11, the searchBar's textField background color is little darker than navigation bar color by default. For consistency, you can change it to white, the below code will work both for iOS11 and its prior:
if let textField = searchController.searchBar.value(forKey: "searchField") as? UITextField {
if let backgroundView = textField.subviews.first {
// Search bar textField background color
backgroundView.backgroundColor = UIColor.white
// Search bar textField rounded corner
backgroundView.layer.cornerRadius = 10
backgroundView.clipsToBounds = true
}
}
I think that the solution is to add the Search Bar in the Navigation Bar:
navigationController?.navigationBar.prefersLargeTitles = true // Navigation bar large titles
navigationItem.title = "Contacts"
navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 0/255, green: 150/255, blue: 136/255, alpha: 1.0)
let searchController = UISearchController(searchResultsController: nil) // Search Controller
navigationItem.hidesSearchBarWhenScrolling = false
navigationItem.searchController = searchController
You can find an example for UISearchBarController - SearchBar and scope buttons overlap here.
I had the same issue in iOS 11.
Contrary to some of the comments here, if I look at your screenshots you DONT want to set it as the navigationItem because you don't have a UINavigationController setup.
Neither do you want to add the searchBar in the header of the tableView because for some reason it can't cope with the scopeBar
So what I did to fix it:
To get a UISearchBar with scopes over your tableView, use a UIViewController in interface builder not a UITableViewController.
Place a UISearchBar and a UITableView inside the view controller and wire them up properly (delegates, dataSource, etc).
Don't forget to change your swift file to UIViewController instead of UITableViewController as well and change it accordingly. (add a tableView property and connect it via IBOutlet, change the delegates for the tableView etc)
Then in interface builder, use autoLayout guides so the searchBar sits on top of the tableView
In interface builder when you activate the scope bar it will look totally weird but don't panic, it will be fine. I guess Apple screwed the rendering n interface builder when they changed the behavior to work with UINavigationController... anyway...
Then everything works as it should and look like this (in my case I present it the vc in a popover but that doesn't matter)

iOS 11 prefersLargeTitles Weird Transition

So I'm having a weird issue with the new large titles in iOS 11. Instead of me trying to badly and confusingly explain the issue here is a 10-second screen recording of what is happening:
Screen recording of issue on YouTube
As you can see there is a weird black bar that appears when transitioning between a view controller that has
navigationItem.largeTitleDisplayMode = .never
And one that is set to .always
Thanks in advance!
Before the transition set this:
self.navigationController?.view.backgroundColor = .white
As Pranav said, the issue here is the background colour of the navigation controller's view, however, changing that from a child view controller is not the perfect way to do it.
Instead, a better way is to subclass UINavigationController and in the viewDidLoad() set the
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = .white
}
Then, just use your custom subclass rather than the standard UINavigationController. This way, you only ever need this code in one place.

Resizing UISearchBar in UINavigationBar titleView doesn't work

Resizing UISearchBar in UINavigationBar titleView doesn't work.
I also got two navigation items on each side of the UINavigationBar.
#IBAction func searchButtonPressed(sender: UIButton) {
searchWrap.frame = self.resultSearchController.searchBar.bounds
searchWrap .addSubview(self.resultSearchController.searchBar)
self.resultSearchController.active = true
self.resultSearchController.searchBar.becomeFirstResponder()
if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
{
self.tableView.tableHeaderView = searchWrap
}
else
{
self.navigationItem.titleView = searchWrap
}
searchIsOn = true
searchButton.hidden = true
filterButton.hidden = true
favButtonStar.hidden = true
settingsButton.hidden = true
}
even if set the frame it automatically resizes.
Here I have created a Demo project for the above solution which you can get it from here.
Download Demo Project
What I have done?
First, I added two buttons to UINavigationBar. First button is for demo and second is for search.
When you tap on search a UISearchBar will be added to the titleView of UINavigationBar and the buttons will be removed from the UINavigationBar
I have implemented the cancel delegate of UISearchBar, when it is called I removed UISearchBar and added the earlier two buttons again.
This how you can get the full UISearchBar
I have met this issue once. And confirm that searchBar that is added as subview on titleView does not work.
titleView belongs to self.navigationController, and your searchDelegate you're using belong to self controller, that's not self.navigationController. So it can not reach into delegate even in debug.
I don't know what your aim, but if you really want to on the navigationBar, you could pretend that, make a view look like a navigationBar, and add searchBar like subview and so on.
Hope this could help.

UISearchController doesn't work properly with a non-translucent UINavigationBar

Currently I am trying to embed a UISearchController into my application. But the UISearchBar, which is a property of the UISearchController, doesn't get displayed properly, if the UINavigationBar is non-translucent. Usually after tapping the UISearchBar property, the UINavigationBar moves up to make room for the UISearchBar. You can see the result on the following screenshot:
https://www.dropbox.com/s/172k63zr2bhj84t/Normal_behaviour.png?dl=0
But if the "translucent" property of the UINavigationBar is set to "NO", the UISearchBar doesn't get displayed properly, because the background of the status bar remains transparent, as you can see on the following screenshot:
https://www.dropbox.com/s/v5cnxoj9ms6976r/Wrong_behaviour.png?dl=0
To demonstrate this weird behaviour, I have modified the sample project provided by Apple:
https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html
Here you can download the modified version:
https://www.dropbox.com/s/7icfe6kap98g1e8/TableSearchwithUISearchControllerObj-CandSwift_MODIFIED.zip?dl=0
The modification is in file "APLMainTableViewController.m" line 33.
It's clearly a bug (rdar://20942583).
My workaround is to set
self.edgesForExtendedLayout = UIRectEdgeAll;
self.extendedLayoutIncludesOpaqueBars = YES;
This allows you to keep the navigation bar opaque. The downside is that the content flows below the bar even if it can't be seen, creating some overhead.
All I needed was:
func viewDidLoad() {
extendedLayoutIncludesOpaqueBars = true
}
One workaround for this is to make the status bar translucent just before the search is going to become active, and remove the translucency when the search is about become inactive.
You can do this by registering your view controller as a delegate of UISearchController, and implementing the willPresentSearchController and willDismissSearchController methods. For example (in Swift):
Declare your view controller as a delegate of UISearchController:
class MyViewController: UITableViewController, UISearchControllerDelegate
Don't forget to actually set it as the delegate, for instance in viewDidLoad add:
searchController.delegate = self
And finally:
func willPresentSearchController(searchController: UISearchController) {
navigationController?.navigationBar.translucent = true
}
func willDismissSearchController(searchController: UISearchController) {
navigationController?.navigationBar.translucent = false
}
Ok, this one is a SUPER pain to debug but not that bad to fix. It's all down to the way Apple changed the appearance of navigation bars. It can be fixed by creating a UINavigationBarAppearance object, configuring it with the visual properties you want (i.e. background colour etc) and then assigning it to standardAppearance and scrollEdgeAppearance on UINavigationBar.appearance() - you can have two different instances with different settings if you want.
A simple implementation might look like this:
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = barColor
appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: textColor]
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
(Naturally replace barColor and textColor with the colours of your choice!)
if someone have a problem like non-translucent hidden the search bar u can just had this :
self.definesPresentationContext = true
Regards

Resources