How to make iOS navigationItem.titleView align to the left? - ios

navigationItem.hidesBackButton = true
navigationItem.leftBarButtonItem = nil
head = UIView()
head.frame = CGRectMake(0, 0, 200, 44)
head.frame.origin.x = CGFloat(0)
navigationItem.titleView = head
I attempt to align the titleView to the left, but it still remains in the middle.

Try this:
let title = UILabel()
title.text = "TITLE"
let spacer = UIView()
let constraint = spacer.widthAnchor.constraint(greaterThanOrEqualToConstant: CGFloat.greatestFiniteMagnitude)
constraint.isActive = true
constraint.priority = .defaultLow
let stack = UIStackView(arrangedSubviews: [title, spacer])
stack.axis = .horizontal
navigationItem.titleView = stack
The idea is that main view (in this case title) will take all the space it needs and spacer view will take all the free space left.

I figured it out.
I just need to set my custom UIView as the leftBarButtonItem.

I had a similar requirement of adding the Title along with the subtitle to the left of the navbar. I couldn't achieve it with a TitleView since it cannot be aligned left.
So I took #TIMEZ and #Wain's answers, along with responses from the thread here and added a complete answer, in case it helps anyone :
let titleLabel = UILabel()
titleLabel.text = "Pillars"
titleLabel.textAlignment = .center
titleLabel.font = .preferredFont(forTextStyle: UIFont.TextStyle.headline)
let subtitleLabel = UILabel()
subtitleLabel.text = "How did you do today?"
subtitleLabel.textAlignment = .center
subtitleLabel.font = .preferredFont(forTextStyle: UIFont.TextStyle.subheadline)
let stackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
stackView.distribution = .equalSpacing
stackView.alignment = .leading
stackView.axis = .vertical
let customTitles = UIBarButtonItem.init(customView: stackView)
self.navigationItem.leftBarButtonItems = [customTitles]

You can't align a title view to the left. You can create a title view and add a subview positioned to its left. If you're looking to display in place of the back button then you should be using a bar button item instead of title view.

I don't think Apple wants you to do that. Navigation bars have a pretty specific purpose that often involves having something else in the top left corner like a Back button. You might be better off making a custom UIView or UIToolbar that looks like the navigation bar.

If it's a custom UIView, override intrinsicContentSize and return
CGSize(width: .greatestFiniteMagnitude, height: UIView.noIntrinsicMetric)
This will stretch the view to the entire width between left and right bar button items.

You can constraint the titleView to the navigationBars leftAnchor.
private func setupNavigationBarTitleView() {
let titleView = YourCustomTitleView()
navigationBarTitleView = titleView
navigationBarTitleView?.translatesAutoresizingMaskIntoConstraints = false
navigationItem.titleView = navigationBarTitleView
if let navigationBar = navigationController?.navigationBar {
NSLayoutConstraint.activate([
titleView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor, constant: 16),
titleView.heightAnchor.constraint(equalToConstant: 36)
])
}
}

The simplest solution is to add low priority constraint for title width.
let titleLabel = UILabel()
titleLabel.textAlignment = .left
...
let c = titleLabe.widthAnchor.constraint(equalToConstant: 10000)
c.priority = .required - 1
c.isActive = true
navigationItem.titleView = titleLabel

Hey guys after trying most of the solutions above. I found that most of em still did not meet my prod requirements. Here is a solution I came up with after trying out different solutions.
func setLeftAlignTitleView(font: UIFont, text: String, textColor: UIColor) {
guard let navFrame = navigationController?.navigationBar.frame else{
return
}
let parentView = UIView(frame: CGRect(x: 0, y: 0, width: navFrame.width*3, height: navFrame.height))
self.navigationItem.titleView = parentView
let label = UILabel(frame: .init(x: parentView.frame.minX, y: parentView.frame.minY, width: parentView.frame.width, height: parentView.frame.height))
label.backgroundColor = .clear
label.numberOfLines = 2
label.font = font
label.textAlignment = .left
label.textColor = textColor
label.text = text
parentView.addSubview(label)
}

let navLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height))
navLabel.text = "Hi, \(CurrentUser.firstName)"
navLabel.textColor = UIColor.white
navLabel.font = UIFont.systemFont(ofSize: 20)
navigationItem.titleView = navLabel

Related

How to reduce the left and right gaps in custom view for Navigation bar in iOS

I recently added a side menu which is having a UITableviewController class as the Menu . In this ViewController i added a custom view to the Navbar through this code. But when i run in device i get extra space on left and right side of the view . How to remove this?
import UIKit
class SettingsTableController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let newView = UIView()
newView.frame = CGRect(x:UIApplication.shared.statusBarFrame.origin.x,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width + 10, height: self.navigationController!.navigationBar.frame.height)
//#710193
newView.backgroundColor = UIColor.red
let lblTitle = UILabel()
lblTitle.text = " Animals"
lblTitle.textColor = UIColor.white
lblTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
lblTitle.frame = newView.bounds
newView.addSubview(lblTitle)
navigationItem.titleView = newView
}
}
so it produces the output as below. I want to remove the pointed out gaps which is shown through red arrows .
You are setting frame but also need to autolayout. So after newView.addSubview(lblTitle) add below codes.
newView.translatesAutoresizingMaskIntoConstraints = false
newView.layoutIfNeeded()
newView.sizeToFit()
newView.translatesAutoresizingMaskIntoConstraints = true
navigationItem.titleView = newView
I have changed some line of code in your code and it is working fine for me
let newView = UIView()
newView.frame = CGRect(x:UIApplication.shared.statusBarFrame.origin.x,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width, height: self.navigationController!.navigationBar.frame.height)
//#710193
newView.backgroundColor = UIColor.red
let lblTitle = UILabel()
lblTitle.text = " Animals"
lblTitle.textColor = UIColor.white
lblTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
lblTitle.frame = newView.bounds
newView.addSubview(lblTitle)
You are adding newView to titleView of navigationItem instead of adding that to navigationBar of navigationController
self.navigationController?.navigationBar.addSubview(newView)
Try to use auto layout constraint programatically in swift. The link is provided below
Auto Layout in Swift: Writing constraints programmatically

Dynamically resize navigation bar title during Large Titles mode

How do I dynamically resize my navigation bar title while in iOS 11's Large Title mode?
Previously you could define your own UILabel as the titleView and have it resize. All it does now is add another titleView on top.
override func viewDidLoad() {
super.viewDidLoad()
self.title = "A very long title. Really long. Dont truncate me though. I want everyone to see me."
let frame = CGRect(x: 0, y: 0, width: 200, height: 40)
let tlabel = UILabel(frame: frame)
tlabel.text = self.title
tlabel.textColor = UIColor.black
tlabel.font = UIFont.boldSystemFont(ofSize: 17)
tlabel.backgroundColor = UIColor.clear
tlabel.adjustsFontSizeToFitWidth = true
tlabel.textAlignment = .center
self.navigationItem.titleView = tlabel
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .automatic
}

How to add a label at bottom of imageView programmatically?

i am trying to add a label at the bottom of imageView as a subview but when image changes its height or width the label is not responsive.
So i want to make a dynamic label.
add like
var lbl1 = UILabel(frame: CGRect(x: yourimageview.frame.origin.x, y: yourimageview.frame.origin.y + yourimageview.frame.size.height + 5, width: yourimageview.frame.size.width, height: asyourWish))
lbl1.textColor = UIColor.black
lbl1.frame = position
lbl1.backgroundColor = UIColor.clear
lbl1.textColor = UIColor.white
lbl1.text = "TEST"
self.view.addSubview(lbl1)
Here example of adding label to image
let picImage:UIImageView = {
let imageView = UIImageView()
let image = UIImage(named: "test")
imageView.image = image
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let durationLabel: UILabel = {
let label = UILabel()
label.text = "1:20:12"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 15.0)
label.textAlignment = NSTextAlignment.right
label.numberOfLines = 1
label.textColor = UIColor.white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupView(){
// I will skip part of image setup
self.picImage.addSubview(durationLabel)
durationLabel.bottomAnchor.constraint(equalTo: picImage.bottomAnchor).isActive = true
durationLabel.leftAnchor.constraint(equalTo: picImage.leftAnchor, constant: 5).isActive = true
durationLabel.rightAnchor.constraint(equalTo: picImage.rightAnchor, constant: -5).isActive = true
}
this code will add label to image that set constraint to bottom and left and right
Try this!
var label = UILabel()
label.frame = CGRect(x: imageView.bounds.origin.x, y: imageView.bounds.origin.y, width: 300, height: 45)
label.backgroundColor = UIColor.orange
label.textAlignment = .left
label.text = "This is a test label"
self.imageView.addSubview(label)

iOS - UIView does not display inside UIStackView

I have a UIStackView which needs a background color in one of the stacks, so I placed a UIView inside, but the UIView is never displayed. The UIView currently has one subview, a UILabel, but should eventually have another UIStackView instead. If I display the UILabel as a direct child of the UIStackView, rather than the UIView, then the UILabel displays properly. So, what constraints are missing or wrong on my UIView?
let stack = UIStackView()
stack.axis = .Vertical
stack.alignment = .Leading
stack.distribution = .EqualCentering
stack.spacing = 0
let width = UIScreen.mainScreen().bounds.size.width
let frame = CGRect(x: 0, y: 0, width: width, height: 50)
let viewHolder = UIView(frame: frame)
viewHolder.backgroundColor = blueColor
//Needs a blue background
let name = UILabel()
name.text = nameText
name.textColor = yellowColor
name.backgroundColor = blueColor
name.font = UIFont.boldSystemFontOfSize(32.0)
let address = UILabel()
address.text = addressText
let dateTime = UILabel()
dateTime.text = calString
viewHolder.addSubview(name)
stack.addArrangedSubview(viewHolder)
stack.addArrangedSubview(address)
stack.addArrangedSubview(dateTime)
self.stackView.addArrangedSubview(stack)
And when run it produces this:
If I remove the UIView from the equation, ie:
let stack = UIStackView()
stack.axis = .Vertical
stack.alignment = .Leading
stack.distribution = .EqualCentering
stack.spacing = 0
let width = UIScreen.mainScreen().bounds.size.width
let frame = CGRect(x: 0, y: 0, width: width, height: 50)
let viewHolder = UIView(frame: frame)
viewHolder.backgroundColor = blueColor
//Needs a blue background
let name = UILabel()
name.text = nameText
name.textColor = yellowColor
name.backgroundColor = blueColor
name.font = UIFont.boldSystemFontOfSize(32.0)
let address = UILabel()
address.text = addressText
let dateTime = UILabel()
dateTime.text = calString
//viewHolder.addSubview(name)
stack.addArrangedSubview(name) //Add the label directly to the UIStackView
stack.addArrangedSubview(address)
stack.addArrangedSubview(dateTime)
self.stackView.addArrangedSubview(stack)
I get:
I just need the blue part to stretch across the screen
So, answer is, don't use UIStackView. Use the built in UITableView for this kind of layout.

Customize navigation bar by adding two labels instead of title in Swift

I am trying to add two labels in the place where the title is shown in navigation bar, but I am struggling to do so. It would be very nice if I could achieve this with storyboard but as I can see I cannot do it.
As I have seen I need to use navigationItem but I do not know how exactly to do that. If anyone have any example or if anyone could explain me more specifically how to do so would be wonderful.
And I need to mention that I am completely unfamiliar with Obj-C, so any help would need to be in Swift.
I am not sure if you can do it from the storyboard, but if you want to add two title labels, you can do the following in the viewDidLoad() method of the view controller for which you want the two titles:
if let navigationBar = self.navigationController?.navigationBar {
let firstFrame = CGRect(x: 0, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
let secondFrame = CGRect(x: navigationBar.frame.width/2, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
let firstLabel = UILabel(frame: firstFrame)
firstLabel.text = "First"
let secondLabel = UILabel(frame: secondFrame)
secondLabel.text = "Second"
navigationBar.addSubview(firstLabel)
navigationBar.addSubview(secondLabel)
}
In this way you can add as many subviews as you want to the navigation bar
Here's an implementation that uses a stack view instead, which also gives you some versatility with layout of the labels:
class ViewController: UIViewController {
lazy var titleStackView: UIStackView = {
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.text = "Title"
let subtitleLabel = UILabel()
subtitleLabel.textAlignment = .center
subtitleLabel.text = "Subtitle"
let stackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
stackView.axis = .vertical
return stackView
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = titleStackView
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if view.traitCollection.horizontalSizeClass == .compact {
titleStackView.axis = .vertical
titleStackView.spacing = UIStackView.spacingUseDefault
} else {
titleStackView.axis = .horizontal
titleStackView.spacing = 20.0
}
}
}

Resources