Is it possible to have the new large titles for navigation bars in iOS 11 show multiple lines? The App Store app does this but I can't find anything in the current documentation to do this. The standard behavior just shows one line with ellipsis if it's too long.
Add following code into viewWillAppear:
navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationItem.largeTitleDisplayMode = .automatic
self.title = "Hello big text, For navigation large style bar"
navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .largeTitle)]
var count = 0
for item in(self.navigationController?.navigationBar.subviews)! {
for sub in item.subviews{
if sub is UILabel{
if count == 1 {
break;
}
let titleLab :UILabel = sub as! UILabel
titleLab.numberOfLines = 0
titleLab.text = self.title
titleLab.lineBreakMode = .byWordWrapping
count = count + 1
}
}
}
self.navigationController?.navigationBar.layoutSubviews()
self.navigationController?.navigationBar.layoutIfNeeded()
Facing issue with back button will update soon..
There is a way to do this simply by using a non-public API. Use at your own risk:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Thunderbox Entertaiment"
navigationItem.enableMultilineTitle()
}
}
extension UINavigationItem {
func enableMultilineTitle() {
setValue(true, forKey: "__largeTitleTwoLineMode")
}
}
Result:
Related
I have a view controller where I need to display multiline title on the navigation bar. For this, I have written a protocol like this -
import UIKit
protocol CustomNavigationBar {
func setupNavigationMultilineTitle(titleText: String, prefersLargeTitles: Bool, largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode)
}
And then extended it -
extension CustomNavigationBar where Self : UIViewController {
func setupNavigationMultilineTitle(titleText: String, prefersLargeTitles: Bool = true, largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode = .automatic ) {
self.navigationController?.navigationBar.prefersLargeTitles = prefersLargeTitles
self.navigationController?.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode
self.navigationController?.navigationBar.largeTitleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .semibold)
]
self.title = titleText
if let navBarSubViews = self.navigationController?.navigationBar.subviews {
for navItem in navBarSubViews {
for itemSubView in navItem.subviews {
if let largeLabel = itemSubView as? UILabel {
largeLabel.text = self.title
largeLabel.numberOfLines = 0
largeLabel.lineBreakMode = .byWordWrapping
largeLabel.sizeToFit()
}
}
}
}
}
}
In my view controller, I conform to this protocol and inside viewDidAppear method, I call setupNavigationMultilineTitle method as follows -
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupNavigationMultilineTitle(titleText: "This is created for testing This is created for testing This is created for testing This is created for testing This is created for testing")
}
**
This works good on an iPhone running lesser than iOS13.
**
**
However, on an iPhone running greater than iOS 13, it just displays
one line and then truncates.
**
Has there been any changes in the UINavigationBar in iOS13? I researched and found something about background color but nothing related to multi line title using prefersLargeTitles and largeTitleDisplayMode.
Can someone please help me getting this up on iOS13?
Thanks!!
In my application I have Scroll View with dynamic height.
Inside it there is one Text View and one Table View - both with dynamic height and scrolling disabled.
These two elements are presented only once per time, so if Text View is visible, then Table View is not.
My issue is that after the screen loaded Scroll View height doesn't get calculated correctly and when you switch for the first time to Table View - it get's covered by background UIView.
Here's how it looks like:
First image - screen just opened, initial position.
Second Image - switched to table view, where it got covered by bg view.
Here's my code:
override func viewDidLoad() {
super.viewDidLoad()
output?.viewIsReady()
setSpeakerData()
contentTableView.register(UINib(nibName: "SpeakerEventsTableViewCell", bundle: nil), forCellReuseIdentifier: "speakerEventsTableViewCell")
}
override func viewWillAppear(_ animated: Bool) {
showSpeakerInfo()
}
func showSpeakerInfo() {
aboutSpeakerTextView.isHidden = false
contentTableView.isHidden = true
aboutSpeakerTextView.sizeToFit()
aboutSpeakerView.backgroundColor = blueColor
eventsView.backgroundColor = UIColor.clear
contentTableViewHeight.constant = aboutSpeakerTextView.frame.height
}
func showSpeakerEvents() {
aboutSpeakerTextView.isHidden = true
contentTableView.isHidden = false
aboutSpeakerView.backgroundColor = UIColor.clear
eventsView.backgroundColor = blueColor
contentTableViewHeight.constant = contentTableView.contentSize.height
contentTableView.reloadData()
}
Strange thing is that when you switch between tabs for several times - everything starts to work properly and Table View doesn't get covered by background UIView.
Would be grateful for any help! Thanks in advance!
Further discovery showed that this bug appears only when text view had 1 lines of text. When it had 2+ lines - it disappeared. I don't know if it's Xcode, Swift or me that led to this)
So, to overcome this bug I've added one line of clear text to my original text received from server and it worked as it should.
This is not a recommended solution, but since it is working - why not.
Here's how my code looks right now:
func setSpeakerData() {
let originalTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(red: 0.41, green: 0.43, blue: 0.51, alpha: 1.0),
NSAttributedString.Key.font: UIFont(name: "Roboto-Light", size: 14.0) as Any]
let dummyTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.clear,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
let partOne = NSMutableAttributedString(string: speaker[0].speakerDetailedText, attributes: originalTextAttributes)
let partTwo = NSMutableAttributedString(string: randomText, attributes: dummyTextAttributes)
let combination = NSMutableAttributedString()
combination.append(partOne)
combination.append(partTwo)
speakerImageView.kf.setImage(with: URL(string: speaker[0].speakerImage), placeholder: UIImage(named: "PlaceholderImage"))
speakerNameLabel.text = speaker[0].speakerName
speakerPositionLabel.text = speaker[0].speakerPosition
aboutSpeakerTextView.attributedText = combination
}
can someone help me out in changing font, size and color in prompt string on my NavigationController?
In the attachment, I want to modify "Consulenze" string.
Thank you everybody
Edit: I already tried the solution found here but no results.
You can try following ways:
1) In viewDidLoad of your ViewController add this lines:
self.navigationController?.navigationBar.tintColor = UIColor.white
let navigationTitleFont = UIFont(name: "Avenir", size: 20)!
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: navigationTitleFont]
2) You can create completely custom nav bar, just add UIView to the top your view and add all necessary elements - buttons, labels, etc.
Simply add this code in your ViewController. You can change both the Prompt text and color by using this code -
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
for view in self.navigationController?.navigationBar.subviews ?? [] {
let subviews = view.subviews
if subviews.count > 0, let label = subviews[0] as? UILabel {
label.textColor = UIColor.red
label.font = UIFont.systemFont(ofSize: 30)
}
}
}
}
OUTPUT -
Additional -
I am unable to change the prompt color on my navigation bar. I've tried the code below in viewDidLoad, but nothing happens.
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
Am I missing something? Is the code above wrong?
I was able to make the prompt color white on iOS 11 was setting the barStyle to black. I set the other color attributes (like the desired background color) using the appearance proxy:
myNavbar.barStyle = UIBarStyleBlack; // Objective-C
myNavbar.barStyle = .black // Swift
It seems like you're right about this one. You need to use UIAppearance to style the prompt text on iOS 11.
I've filed radar #34758558 that the titleTextAttributes property just stopped working for prompt in iOS 11.
The good news is that there are a couple of workarounds, which we can uncover by using Xcode's view hierarchy debugger:
// 1. This works, but potentially changes *all* labels in the navigation bar.
// If you want this, it works.
UILabel.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).textColor = UIColor.white
The prompt is just a UILabel. If we use UIAppearance's whenContainedInInstancesOf:, we can pretty easily update the color the way we want.
If you look closely, you'll notice that there's also a wrapper view on the UILabel. It has its own class that might respond to UIAppearance...
// 2. This is a more precise workaround but it requires using a private class.
if let promptClass = NSClassFromString("_UINavigationBarModernPromptView") as? UIAppearanceContainer.Type
{
UILabel.appearance(whenContainedInInstancesOf: [promptClass]).textColor = UIColor.white
}
I'd advise sticking to the more general solution, since it doesn't use private API. (App review, etc.) Check out what you get with either of these two solutions:
You may use
for view in self.navigationController?.navigationBar.subviews ?? [] {
let subviews = view.subviews
if subviews.count > 0, let label = subviews[0] as? UILabel {
label.textColor = UIColor.white
label.backgroundColor = UIColor.red
}
}
It will be a temporary workaround until they'll fix it
More complicated version to support old and new iOS
func updatePromptUI(for state: State) {
if (state != .Online) {
//workaround for SOFT-7019 (iOS 11 bug - Offline message has transparent background)
if #available(iOS 11.0, *) {
showPromptView()
} else {
showOldPromptView()
}
}
else {
self.navigationItem.prompt = nil
if #available(iOS 11.0, *) {
self.removePromptView()
} else {
self.navigationController?.navigationBar.titleTextAttributes = nil
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.lightGray]
}
}
}
private func showOldPromptView() {
self.navigationItem.prompt = "Network Offline. Some actions may be unavailable."
let navbarFont = UIFont.systemFont(ofSize: 16)
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: navbarFont, NSAttributedStringKey.foregroundColor:UIColor.white]
}
private func showPromptView() {
self.navigationItem.prompt = String()
self.removePromptView()
let promptView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 18))
promptView.backgroundColor = .red
let promptLabel = UILabel(frame: CGRect(x: 0, y: 2, width: promptView.frame.width, height: 14))
promptLabel.text = "Network Offline. Some actions may be unavailable."
promptLabel.textColor = .white
promptLabel.textAlignment = .center
promptLabel.font = promptLabel.font.withSize(13)
promptView.addSubview(promptLabel)
self.navigationController?.navigationBar.addSubview(promptView)
}
private func removePromptView() {
for view in self.navigationController?.navigationBar.subviews ?? [] {
view.removeFromSuperview()
}
}
I suggest using a custom UINavigationBar subclass and overriding layoutSubviews:
- (void)layoutSubviews {
[super layoutSubviews];
if (self.topItem.prompt) {
UILabel *promptLabel = [[self recursiveSubviewsOfKind:UILabel.class] selectFirstObjectUsingBlock:^BOOL(UILabel *label) {
return [label.text isEqualToString:self.topItem.prompt];
}];
promptLabel.textColor = self.tintColor;
}
}
Basically I'm enumerating all UILabels in the subview hierarchy and check if their text matches the prompt text. Then we set the textColor to the tintColor (feel free to use a custom color). That way, we don't have to hardcode the private _UINavigationBarModernPromptView class as the prompt label's superview. So the code is be a bit more future-proof.
Converting the code to Swift and implementing the helper methods recursiveSubviewsOfKind: and selectFirstObjectUsingBlock: are left as an exercise to the reader 😉.
You can try this:
import UIKit
class ViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updatePrompt()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updatePrompt()
}
func updatePrompt() {
navigationItem.prompt = " "
for view in navigationController?.navigationBar.subviews ?? [] where NSStringFromClass(view.classForCoder) == "_UINavigationBarModernPromptView" {
if let prompt = view.subviews.first as? UILabel {
prompt.text = "Hello Red Prompt"
prompt.textColor = .red
}
}
navigationItem.title = "This is the title (Another color)"
}
}
Moshe's first answer didn't work for me because it changed the labels inside of system VCs like mail and text compose VCs. I could change the background of those nav bars but that opens up a whole other can of worms. I didn't want to go the private class route so I only changed UILabels contained inside of my custom navigation bar subclass.
UILabel.appearance(whenContainedInInstancesOf: [NavigationBar.self]).textColor = UIColor.white
Try this out:->
navController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.red]
I've found next work around for iOS 11.
You need set at viewDidLoad
navigationItem.prompt = UINavigationController.fakeUniqueText
and after that put next thing
navigationController?.promptLabel(completion: { label in
label?.textColor = .white
label?.font = Font.regularFont(size: .p12)
})
extension UINavigationController {
public static let fakeUniqueText = "\n\n\n\n\n"
func promptLabel(completion: #escaping (UILabel?) -> Void) {
gloabalThread(after: 0.5) { [weak self] in
guard let `self` = self else {
return
}
let label = self.findPromptLabel(at: self.navigationBar)
mainThread {
completion(label)
}
}
}
func findPromptLabel(at view: UIView) -> UILabel? {
if let label = view as? UILabel {
if label.text == UINavigationController.fakeUniqueText {
return label
}
}
var label: UILabel?
view.subviews.forEach { subview in
if let promptLabel = findPromptLabel(at: subview) {
label = promptLabel
}
}
return label
}
}
public func mainThread(_ completion: #escaping SimpleCompletion) {
DispatchQueue.main.async(execute: completion)
}
public func gloabalThread(after: Double, completion: #escaping SimpleCompletion) {
DispatchQueue.global().asyncAfter(deadline: .now() + after) {
completion()
}
}
I want to add uisearchbar in place of title of controller.
I am facing 2 problems currently.
1)
I do not know from where this gray background is coming. Please check this picture.
2) I need this searchbar in other inner screens also. But when I push another controller this searchbar is removed.
Here is my code :
// Seachbar Container View
let searchBarContainer = ERView(frame: CGRectMake(0,0,280,44))
searchBarContainer.autoresizingMask = [.FlexibleWidth]
searchBarContainer.backgroundColor = UIColor.clearColor()
// Search Bar
let searchBar = ERSearchBar(frame: searchBarContainer.bounds)
searchBarContainer.addSubview(searchBar)
// Add View as Title View in Navigation Bar
self.navigationController!.navigationBar.topItem?.titleView = searchBarContainer
Here is Code of my UISearchBar Class
func commonInit() -> Void {
// Update UI
if let searchField = self.valueForKey("searchField") as? UITextField{
// To change background color
searchField.backgroundColor = UIColor.appNavigationBarDarkRedColor()
// Tint Color
if let leftViewRef = searchField.leftView {
leftViewRef.tintColor = UIColor.whiteColor()
}else if let imgLeftView = searchField.leftView as? UIImageView{
imgLeftView.tintColor = UIColor.whiteColor()
}
// Font Color
searchField.font = UIFont.robotoRegularFont(WithSize: 14.0)
// Text Color
searchField.textColor = UIColor.whiteColor()
// PlaceHolder Attributes
searchField.attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()])
}
self.setImage(UIImage(named: "ic_search_white"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
// To change placeholder text color
}
Please someone help me here.
For 1) Set the searchBarStyle property to minimal. This will provides no default background color in UIsearchBar.
2)I'm not quite sure what'd you mean by "inner screen". But if what you want is a Search Bar that can work across different view controllers, UISearchController is the one you're looking for.
You can fine the Apple sample code here