Last updated on: May 27, 2023
In this tutorial, I’m going to show how to add padding in UILabel using Swift without needed any third-party library.
On the Internet, many people suggest using UITextView to be able to have padding in your text, because iOS doesn’t support padding in UILabel.
Today, I’ll show you an easy way to have padding in UILabel too!
Contents
Adding Padding Support in UILabel
First, create a new swift file and name it PaddingLabel
Then, paste the following code inside:
import Foundation
import UIKit
@IBDesignable
class PaddingLabel: UILabel {
var textEdgeInsets = UIEdgeInsets.zero {
didSet { invalidateIntrinsicContentSize() }
}
open override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: textEdgeInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textEdgeInsets.top, left: -textEdgeInsets.left, bottom: -textEdgeInsets.bottom, right: -textEdgeInsets.right)
return textRect.inset(by: invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textEdgeInsets))
}
@IBInspectable
var paddingLeft: CGFloat {
set { textEdgeInsets.left = newValue }
get { return textEdgeInsets.left }
}
@IBInspectable
var paddingRight: CGFloat {
set { textEdgeInsets.right = newValue }
get { return textEdgeInsets.right }
}
@IBInspectable
var paddingTop: CGFloat {
set { textEdgeInsets.top = newValue }
get { return textEdgeInsets.top }
}
@IBInspectable
var paddingBottom: CGFloat {
set { textEdgeInsets.bottom = newValue }
get { return textEdgeInsets.bottom }
}
}
Code language: Swift (swift)
Using Padding in UILabel
Storyboard
If you’re using storyboards, after you have added the label in your view, add the PaddingLabel class as a Custom Class
Next, select the Attribute Inspector and add the padding:
Programmatically
If you have created an UILabel programmatically, replace the UILabel class with the PaddingLabel and add the padding:
// Init Label
let label = PaddingLabel()
label.backgroundColor = .black
label.textColor = .white
label.font = .systemFont(ofSize: 26, weight: .semibold)
label.text = "UILabel with Padding"
self.view.addSubview(label)
// Padding
label.paddingLeft = 15
label.paddingRight = 15
label.paddingTop = 8
label.paddingBottom = 8
// ...
Code language: Swift (swift)
You can find the final project here
If you have any questions, please feel free to leave a comment below