UILabel

Janvi Arora
3 min readMar 7, 2023

--

A UIView that displays text.

Inheritance:

Object ⇾ NSObject ⇾ UIResponder ⇾ UIView ⇾ UILabel

Creating a UILabel

let frame = CGRect(x: 0, y: 0, width: 200, height: 21)
let label = UILabel(frame: frame)
view.addSubview(label)

Background Color and AutoLayouts

// Adding background color and using AutoLayout to set constraints
let label = UILabel()
label.backgroundColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)

Number of lines

// Infinte number of lines can be there
label.numberOfLines = 0

// Only one line of label will be there. If the text outlies the width of label, then it will end with three consecutive dots (Label...)
label.numberOfLines = 1

Set fonts

label.font = UIFont.systemFont(ofSize: 17)

// with weight
label.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightBold)

// bold syle
label.font = UIFont.boldSystemFont(ofSize: 17)

// font style
label.font = UIFont.preferredFont(forTextStyle: .body)

// font size
label.font = label.font.withSize(15)

Function sizeToFit()

The sizeToFit() method resizes the view so that it fits its content. For example, if you have a label with text that is too long to fit within its current frame, calling sizeToFit() will resize the label to fit the text without truncating it.

let myLabel = UILabel()
myLabel.text = "This is some really long text that won't fit within the label's frame"
myLabel.sizeToFit()

Text alignment

label.textAlignment = NSTextAlignment.left

//or the shorter
label.textAlignment = .left

Any value in the NSTextAlignment enum is valid: .left, .center, .right, .justified, .natural

Clickable Label

  1. Create label
  2. Enable user interaction
  3. Add UITapGestureRecognizer
let label = UILabel()
label.userInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(labelClicked(_:)))
label.addGestureRecognizer(gesture)

@objc func labelClicked() {
//.....
}

Variable height using constraints

You can make an UILabel with a dynamic height using auto layout. You need to set the numberOfLines to zero (0), and add a minimal height by setting up a constraints with a relation of type .greaterThanOrEqualTo on the .height attribute.

label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.heightAnchor.constraintGreaterThanOrEqualToConstant(20).active = true

Line Break Modes

the lineBreakMode property is used to specify how text should be handled when it exceeds the width of a view. There are several different lineBreakMode options available:

  1. .byWordWrapping: Wraps the text to the next line at the nearest word boundary, which means that the text won't be broken up in the middle of a word.
  2. .byCharWrapping: Wraps the text to the next line at any character boundary, which means that the text can be broken up in the middle of a word.
  3. .byClipping: Clips the text so that any characters that don't fit within the view's bounds are not shown.
  4. .byTruncatingHead: Truncates the text at the beginning of the string and adds an ellipsis at the end of the truncated string.
  5. .byTruncatingTail: Truncates the text at the end of the string and adds an ellipsis at the end of the truncated string.
  6. .byTruncatingMiddle: Truncates the text in the middle of the string and adds an ellipsis at the beginning and end of the truncated string.
label.lineBreakMode = .byTruncatingTail

Add shadows to text

label.layer.shadowOffset = CGSize(width: 3, height: 3)
label.layer.shadowOpacity = 0.7 // Range: 0-1
label.layer.shadowRadius = 2

Changing text in the existing label

label.text = "Give your new text string"

Highlighted and highlighted text color

let label = UILabel()
label.isHighlighted = true
label.highlightedTextColor = UIColor.red

Dynamic label frame from an unknown text

var message: String = "Some dynamic text for label"

//set the text and style if any.
label.text = message
label.numberOfLines = 0

var maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
var expectedLabelSize: CGSize = label.sizeThatFits(maximumLabelSize)

// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = label.frame

// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height

// put calculated frame into UILabel frame
label.frame = newFrame

Underlining text

let label = UILabel.init(frame: CGRect(x: 0, y:0, width: 100, height: 40))
label.backgroundColor = .lightGray
let attributedString = NSMutableAttributedString.init(string: "Apply UnderLining")
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range:
NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString

--

--

No responses yet