How we can add additional UILabels to UINavigation? - ios

I would like to add a cycle view and a label to UINavigation. like this:
I can set a label to my UINavigation by this code:
if let navigationBar = self.navigationController?.navigationBar {
let firstFrame = CGRect(x: 300, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
let firstLabel = UILabel(frame: firstFrame)
firstLabel.text = "First"
navigationBar.addSubview(firstLabel)
}
but I have two problems by this code:
1.how to set x position correctly?
(to test I set 300 value, but this value show different position on different screen sizes)
2. how to set a cycle background to this label ?

You can add both of the view (red circle) and the label (number 16) programmatically as a subView to the button of the bar button item.
What you should do is:
Connect the button as an IBOutlet to its ViewController:
Make sure that the connected component is the UIButton, but NOT UIBarButtonItem.
As you can see, I called it btnMenu.
Create your views (red circle and number label) and add it to the btnMenu:
It should be similar to:
import UIKit
class ViewController: UIViewController {
//...
#IBOutlet weak var btnMenu: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//...
// setup the red circle UIView
let redCircleView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
redCircleView.backgroundColor = UIColor.red
redCircleView.layer.cornerRadius = view.frame.size.width / 2
// setup the number UILabel
let label = UILabel(frame: CGRect(x: 4, y: 0, width: 20, height: 20))
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 10)
label.text = "16"
// adding the label into the red circle
redCircleView.addSubview(label)
// adding the red circle into the menu button
btnMenu.addSubview(redCircleView)
//...
}
//...
}
And that's it!
UIButton is a subclass of UIView, meaning that you can add subviews to it (add​Subview(_:​)).
Output:
Hope this helped.

Related

Swift & UILabel : How to add padding and margin in Swift programmatically? [duplicate]

This question already has answers here:
Add padding between label and its border
(4 answers)
Closed 8 months ago.
I have created a text programmatically with a grey background using UILabel.
Now I would like to add padding to this paragraph/text. Also, it would be great if you could show me how to add margin to my UILabel as well.
import UIKit
final class SignUpViewController: UIViewController {
public let identifier = "Sign Up"
private let logoImage : UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "MyLogoWithTitle")
imageView.clipsToBounds = true
return imageView
}()
private let instructionText : UILabel = {
let label = UILabel()
label.text = "Please read terms and conditions below carefully before proceeding with the registration."
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
label.numberOfLines = 0
label.tintColor = .white
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(logoImage)
view.addSubview(instructionText)
view.backgroundColor = UIColor().colorFromHex(hex: "#141920", opacity: 1.0)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
logoImage.frame = CGRect(x: 0,
y: 0,
width: 140,
height: 60)
logoImage.center = CGPoint(x: view.center.x, y: view.height/5)
instructionText.frame = CGRect(
x: 5,
y: 5 + logoImage.bottom,
width: view.width - 20,
height: 50)
.integral
instructionText.layer.cornerRadius = 10
}
}
Notice that I created an extension to UIColor so that I can input hex color in this way - UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4) .
I am looking forward to hearing from you. Thank you.
You can insert this UILabel into the container (any UIView) and set its position inside.
But the simplest trick is to use UIButton instead of UILabel. You can configure UIEdgeInsets for padding.
So that UIButton does not act as a button simply set button.isUserInteractionEnabled = false.
By default, text in the button are placed in the center, but its position is easy to change with contentHorizontalAlignment and contentVerticalAlignment
And as a bonus, you can add icons right near to the text. :)
UPD.
Could you give me a simple example? I tried that way but I didn't get the result I expected. – Punreach Rany
let buttonUsedAsLabel = UIButton()
// Your question was about padding
// It's it!
buttonUsedAsLabel.titleEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
// Make it not user interactable as UILabel is
buttonUsedAsLabel.isUserInteractionEnabled = false
// set any other properties
buttonUsedAsLabel.setTitleColor(.white, for: .normal)
buttonUsedAsLabel.contentVerticalAlignment = .top
buttonUsedAsLabel.contentHorizontalAlignment = .left
// Set title propeties AFTER it was created with text because it's nullable
// You can use attributed title also
// Never use any (button.titleLabel) before its creation
// for example: (button.titleLabel?.text = "zzz") do nothing here
buttonUsedAsLabel.setTitle("This is the text", for: .normal)
buttonUsedAsLabel.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium)
buttonUsedAsLabel.titleLabel?.numberOfLines = 0
buttonUsedAsLabel.titleLabel?.lineBreakMode = .byWordWrapping
// and so on
// ...
// This is the triсk :)
Of course, you can do it with a storyboard if prefer.
1. Add this class
PaddingLabel.swift
import UIKit
class PaddingLabel: UILabel {
var edgeInset: UIEdgeInsets = .zero
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: edgeInset.top, left: edgeInset.left, bottom: edgeInset.bottom, right: edgeInset.right)
super.drawText(in: rect.inset(by: insets))
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + edgeInset.left + edgeInset.right, height: size.height + edgeInset.top + edgeInset.bottom)
}
}
2. Add this code to your ViewController
let label = PaddingLabel()
override func viewDidLoad() {
super.viewDidLoad()
label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
//Setting the padding label
label.edgeInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
The answer to the link below is that I wrote the same content based on the storyboard.
Add padding between label and its border
I use textfield. Set padding and text in textfield. And do not allow editing.
extension UITextField {
func addLeftPadding() {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = ViewMode.always
}
}
//ViewController
#IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.addLeftPadding()
myTextField.isUserInteractionEnabled = false
myTextField.text = "your label text"
}

Overlap UIButton on two or more views on swift

I am trying to overlap the button on two or more views. So when I add this on the first view it is not showing on the second view so I want one button must shown on two views.
You can make two views and embed second view to first and then button to second View and can play with its Y axis
class overlapViewcontroller:UIViewController {
private let firstView:UIView = {
let view = UIView(frame: CGRect(x: 10,
y: 100,
width: 350,
height: 50))
view.backgroundColor = .green
return view
}()
private let secondView:UIView = {
let view = UIView(frame: CGRect(x: 10,
y: 10,
width: 330,
height: 30))
view.backgroundColor = .purple
return view
}()
private let button:UIButton = {
let button = UIButton(frame: CGRect(x: 10,
y: -5,
width: 310,
height: 20))
button.setTitle("Button", for: .normal)
button.backgroundColor = .systemOrange
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(firstView)
firstView.addSubview(secondView)
secondView.addSubview(button)
}
}
Did you try this? You need to add the button to the container subview and add
this line container.bringSubviewToFront(button)
https://www.hackingwithswift.com/example-code/uikit/how-to-bring-a-subview-to-the-front-of-a-uiview
You need either to
add the button as the very last so that it can be the top one on the subviews stack
or to apply the superview.bringSubviewToFront(button)

Change label text in the navigation bar

I added a label to my NavigationBar with this code:
let navigationBar = self.navigationController?.navigationBar
let moneyFrame = CGRect(x: 330, y: 0, width: (navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)
let moneyLabel = UILabel(frame: moneyFrame)
moneyLabel.text = "\(money)"
navigationBar?.addSubview(moneyLabel)
The problem is: when I want to change the value of the variable "money", I always came with the solution to add another label. I just want to change the text of the label in the NavigationBar.
In the class scope define a label like this:
var moneyLabel: UILabel?
then in your function or wherever the code you posted sits in the class, do this:
func myFunctionThatSetupNavigationLabel() {
let navigationBar = self.navigationController?.navigationBar
let moneyFrame = CGRect(x: 330, y: 0, width:
(navigationBar?.frame.width)!/2, height: (navigationBar?.frame.height)!)
moneyLabel = UILabel(frame: moneyFrame)
moneyLabel.text = "\(money)"
navigationBar?.addSubview(moneyLabel)
}
Now just add this function to edit the title label:
func updateTitle(title: String) {
if let myTitleView = self.moneyLabel {
myTitleView.text = title
}
}
You could add the label to the navigation bar as a custom view.
In the class scope define a label:
var label = UILabel()
then in viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
let textlabel = UIBarButtonItem(customView: label)
navigationItem.rightBarButtonItem = textlabel
label.text = "money"
}
then whenever you want to change the text label you could simply just write the next code:
label.text = "whatever you want"

Why setting titleView lowers header text?

I'm trying to dynamically set my navigation bar's text so that the header text always fits. I'm acccomplishing that like this:
// Pet's Day text "Joy's Day"
if let range = currentPet.range(of: "_") {
let petsName = currentPet[range.upperBound..<currentPet.endIndex]
let deviceWidth = UIScreen.main.bounds.size.width
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth, height: 40))
titleLabel.text = "\(petsName)'s Day"
titleLabel.font = UIFont.systemFont(ofSize: 30)
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.5
titleLabel.textAlignment = .center
self.navBar.topItem?.titleView = titleLabel
}
However, as seen by this picture, this lowers the header text below its natural height:
The navigation bar on the left is from one of my app's other views, while the one on the right is the one I'm setting.
Both of these navigation bars are navigation bars that I've dragged in and made the prompt equal to an empty string to increase their height:
Can anybody please help me implement my code above so that it doesn't drop down the header text?
**Edit: Here are screenshots from Xcode's debug hierarchy:
This is the normal navigation bar:
This is the one I'm setting:
You need to set the baseline, by default is Align Baseline, you need to change to Align Centers
Code example:
class TestViewController: UIViewController {
#IBOutlet weak var navBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
// Change the height of the navbar
self.navBar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 68)
let deviceWidth = UIScreen.main.bounds.size.width
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: deviceWidth, height: 40))
titleLabel.text = "Log Events" // Change to Joy's Day and check the result
titleLabel.font = UIFont.systemFont(ofSize: 30)
titleLabel.baselineAdjustment = .alignBaselines
titleLabel.textColor = UIColor.white
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = 0.5
titleLabel.textAlignment = .center
self.navBar.topItem?.titleView = titleLabel
}
}

How to set a button to most right side of navigation - iOS

I set a button to right side of navigation bar:
my view controller:
I want to set a burger icon,red cycle and a label to this button. like this:
my code:
self.navigationController?.navigationBar.barTintColor = self.utilities.hexStringToUIColor(hex: "#00b8de")
var imageview2 = UIImage(named: "menulogo")
imageview2 = imageview2?.imageResize(sizeChange: CGSize(width: 25, height: 25))
btnMenu.setImage(imageview2,for:UIControlState.normal)
btnMenu.setTitle("", for: .normal)
// setup the red circle UIView
let redCircleView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
redCircleView.backgroundColor = UIColor.red
redCircleView.layer.cornerRadius = view.frame.size.width / 2
// setup the number UILabel
let label = UILabel(frame: CGRect(x: 30, y: 0, width: 20, height: 20))
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 10)
label.text = "16"
// adding the label into the red circle
redCircleView.addSubview(label)
// adding the red circle into the menu button
btnMenu.addSubview(redCircleView)
with above codes I have three problems:
my burger image isn't in most right side of navigation.
my cycle view doesn't show
my icon is white, but it shows blue!
btnMenu is my button in navigation.
I have use this library for set badge on navigation button.
MIBadgeButton is badge button written in Swift with high
UITableView/UICollectionView performance.
https://github.com/mustafaibrahim989/MIBadgeButton-Swift

Resources