Issue creating a large title navigation bar with 2 lines | Swift 5 - swift

Essentially I would like to create a double line large title navigation bar for iOS 14 - I cannot seem to find a conclusive answer anywhere.
The following is what I currently have:
title = "Good Morning \nTim"
for navItem in(self.navigationController?.navigationBar.subviews)! {
for itemSubView in navItem.subviews {
if let largeLabel = itemSubView as? UILabel {
largeLabel.text = self.title
largeLabel.numberOfLines = 0
largeLabel.lineBreakMode = .byWordWrapping
}
}
}
The issue with this is does display the second line, so the text is cutting off at Good Morning.
Any suggestions?

Your ViewController needs this modification in viewDidLoad for example:
let label = UILabel()
label.numberOfLines = 2
label.textAlignment = .center
label.text = "Good Morning \nTim"
navigationItem.titleView = label

Related

Adding labels and textviews in a stack view programmatically in swift

How can I do to have a title, followed by a few lines of text, followed by a title again and again few lines of text constrained in the middle of a view controller programmatically?
My goal is to have bolded for the titles, and it would be nice to have the textview lines incremented also.
My idea was to create 2 labels, and 2 textviews. And adding those to a textview in this order: label1, t1, label2, t2.
But it doesn't seem to work. I try to avoid defining the same textviews and labels many times. textviews add up if I copy its definition twice but not for labels (maybe it is view related?)
I tried with UIbuttons and it worked.
This is what I tried so far:
import UIKit
class HowToSetupProIGVC: UIViewController {
deinit {print("deinit")}
let textView: UITextView = {
let textView = UITextView()
textView.backgroundColor = .blue //bkgdColor
textView.textAlignment = .left
//textView.frame = CGRect(x: 5, y: 5, width: 5, height: 5)
textView.tintColor = .black
textView.translatesAutoresizingMaskIntoConstraints = false //enable autolayout
textView.heightAnchor.constraint(equalToConstant: 100).isActive = true
textView.widthAnchor.constraint(equalToConstant: 300).isActive = true
return textView
}()
let label: UILabel = {
let l = UILabel(frame:CGRect.zero)
//l.frame = CGRect(x: 5, y: 5, width: 5, height: 5)
l.backgroundColor = .green //bkgdColor
l.font = UIFont.preferredFont(forTextStyle: .headline)
l.translatesAutoresizingMaskIntoConstraints = false //enable autolayout
l.heightAnchor.constraint(equalToConstant: 22).isActive = true
l.widthAnchor.constraint(equalToConstant: 300).isActive = true
return l
}()
override func viewDidLoad() {
super.viewDidLoad()
self.modalUI(arrowButton: false)
self.view.backgroundColor = bkgdColor
customStackHTSProIG ()
}
}
extension HowToSetupProIGVC {
func customStackHTSProIG () {
let label1 = label
let label2 = label
let t1 = textView
let t2 = textView
label1.text = "Title1:"
label2.text = "title2:"
t1.text = """
1. On your profile tap menu
2. Tap settings
3. Tap accounts
4. Tap set up professional account
"""
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
//StackView
let stackHTS = UIStackView()
stackHTS.axis = NSLayoutConstraint.Axis.vertical
stackHTS.distribution = .fillEqually
stackHTS.alignment = .center
stackHTS.spacing = 5
stackHTS.backgroundColor = .red
//Add StackView + elements
stackHTS.addArrangedSubview(label1)
stackHTS.addArrangedSubview(t1)
stackHTS.addArrangedSubview(label2)
stackHTS.addArrangedSubview(t2)
self.view.addSubview(stackHTS)
//Constraints StackView
stackHTS.translatesAutoresizingMaskIntoConstraints = false
stackHTS.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
stackHTS.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
//stackHTS.heightAnchor.constraint(equalToConstant: 88).isActive = true
}
}
UILabel & UITextView are both UIKit classes written in Objective-C. They are reference types, NOT value types.
When you write following -
let label1 = label
let label2 = label
let t1 = textView
let t2 = textView
Both label1 & label2 are pointing to the one & same instance of UILabel. So is the case for t1 & t2 as well.
When you add them like this -
//Add StackView + elements
stackHTS.addArrangedSubview(label1)
stackHTS.addArrangedSubview(t1)
stackHTS.addArrangedSubview(label2)
stackHTS.addArrangedSubview(t2)
You expect 2 labels and 2 textViews to be added to the StackView. You are adding only 1 label and 1 textView though.
You expect to see all of following -
label1.text = "Title1:"
label2.text = "title2:"
t1.text = """
1. On your profile tap menu
2. Tap settings
3. Tap accounts
4. Tap set up professional account
"""
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
However you are only seeing following -
label2.text = "title2:"
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
Solutions -
Create two separate instances of UITextView & UILabel like you have already done for the first two and Add these new instances to stack view as well.
Use one UILabel and remove everything else. Use NSAttributedString API to stylize your text as you want for different sections / paragraphs and assign it to UILabel.attributedText.

Setting a variable to a defined lazy var within a UIView closure cause reference problems

Recently, I was working on a project of mine and I wanted to have multiple labels with the same font, text color, and properties, except their text.
This is the code I wrote:
lazy var profileLabel: UILabel = {
let label = UILabel()
label.font = .displayNameLabel
label.textColor = .profileLabel
label.numberOfLines = .numberOfLines
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var displayName: UILabel = {
let label = profileLabel
label.text = "Kevin"
return label
}()
lazy var countryLabel: UILabel = {
let label = profileLabel
label.text = "US"
return label
}()
As you can see, to remedy my issue, I created a single label that had all the properties I wanted for all my other labels. For my other labels, I thought I was creating a new label by typing let label = profileLabel. But as it turns out, I wasn't. After consecutive calls of setting the text and adding the labels to my view, only 1 label was actually displayed, and it was the last label added; so in this case, it would be the countryLabel.
It seems to me that in all my calls to let label = profileLabel, I'm just creating a reference to the same profileLabel. And if this is the case, would changing lazy var profileLabel to var profileLabel fix this issue and create a new label with the needed properties every time profileLabel is called?
You were intended to use computed property of swift. But didn’t get it right. Your profile label should have been defined as follows.
var profileLabel: UILabel {
get {
let label = UILabel()
label.font = .displayNameLabel
label.textColor = .profileLabel
label.numberOfLines = .numberOfLines
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
}

How to setup constraints with SnapKit for UITextField and UILabel?

I have a [[TextField need max available width----]offset(10.0)][Label]]. I want to setup TextFeild pin to left and shrink all available space without label trimming and setup label to pin right and get minimal fit size.
lazy var textField: UITextField = {
var textField = UITextField()
textField.placeholder = "Placeholder"
textField.delegate = self
textField.borderStyle = UITextField.BorderStyle.none
textField.keyboardType = UIKeyboardType.numberPad
textField.returnKeyType = UIReturnKeyType.done
textField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return textField
}()
lazy var measureLabel: UILabel = {
var label = UILabel()
label.numberOfLines = 1
label.setContentHuggingPriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}()
measureLabel.snp.makeConstraints { (make) in
make.right.equalTo(self.snp.right)
make.centerY.equalToSuperview()
}
textField.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.right.equalTo(self.measureLabel.snp.left).offset(-10.0)
make.centerY.equalToSuperview()
}
You need
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .horizontal)
Also you can completely remove these 2 lines as by default textfield's ContentHuggingPriority && ContentCompressionResistancePriority is lower than the default for label , plus the textfield has no intrinsic size
Implement the a demo below.
label can automatically increase height with attributes below. (swift 5)
label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
It can make the height of super view synchronize at the same time, when you set
the height of super view the same as label.
label = UILabel()
viewContainer.addSubview(label)
label.backgroundColor = UIColor.white
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.text = "hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day. hello world, today is a new day. Have a nice day."
self.addSubview(label)
label.snp.makeConstraints { (make) in
let superView = viewContainer!
make.left.equalTo(superView).offset(10)
make.right.equalTo(superView).offset(-10)
make.centerY.equalTo(superView)
}
viewContainer.snp.makeConstraints { (make) in
make.centerY.equalTo(self)
make.centerX.equalTo(self)
make.left.equalTo(self).offset(10)
make.right.equalTo(self).offset(-10)
make.height.equalTo(label).offset(100)
}
download code: https://github.com/zgpeace/SnapkitDemo/tree/dynamicHeightLabel

Curve search bar Swift 4 [duplicate]

This question already has answers here:
UISearchBar custom corners
(5 answers)
Closed 4 years ago.
i had problem to change my search bar design programatically on navigation controller. i just want to make the search bar curve like image below:
i had try a lot of example in stack overflow, but i still failed to change the shape. Here what it looks like now:
and here is the source code, on what have already done:
//MARK for searchBar UI
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.placeholder = " Search for programs..."
searchController.searchBar.sizeToFit()
searchController.searchBar.isTranslucent = false
searchController.searchBar.backgroundImage = UIImage()
searchController.searchBar.delegate = self
navigationItem.titleView = searchController.searchBar
self.searchController.searchBar.layer.cornerRadius = 20.0
self.searchController.searchBar.clipsToBounds = true
// SearchBar text
let textFieldInsideUISearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideUISearchBar?.borderStyle = .roundedRect
textFieldInsideUISearchBar?.font = textFieldInsideUISearchBar?.font?.withSize(14)
and now, i really have no idea how to change it, thanks in advance.
This will help you,
let searchBar = UISearchBar()
On viewDidLoad()
searchBar.sizeToFit()
searchBar.placeholder = "Search"
self.navigationController?.navigationBar.barTintColor = UIColor.green //this is just for reference
self.navigationItem.titleView = searchBar
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
backgroundview.backgroundColor = UIColor.blue
backgroundview.layer.cornerRadius = 20;
backgroundview.clipsToBounds = true;
}
}
Above code will give you following output,
increasing the corner radius should work

How does NSCollectionView draw text without item?

I've seen a lot of APP listing articles in NSCollectionView. When there is no item, there are some hints in the middle of view, such as "no articles", "waiting to add", and so forth.
Do you have any relevant cases to show me how this is accomplished?.
Thank you
Try this code:
func showMessage(_ text: String) {
let messageLabel = UILabel()
messageLabel.text = text
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
self.collectionView.backgroundView = messageLabel
}
func hideMessage() {
self.collectionView.backgroundView = nil
}