How To Add Padding To Uilabel Swift
In this tutorial, I'm going to show how to add padding in UILabel using Swift without needed whatever 3rd-party library.
On the Internet, many people suggest using UITextView to be able to accept padding in your text, because iOS doesn't support padding in UILabel.
Today, I'll evidence you an like shooting fish in a barrel mode to have padding in UILabel too!
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.tiptop, left: -textEdgeInsets.left, lesser: -textEdgeInsets.lesser, right: -textEdgeInsets.right) render textRect.inset(by: invertedInsets) } override func drawText (in rect: CGRect) { super.drawText(in: rect.inset(past: textEdgeInsets)) } @IBInspectable var paddingLeft: CGFloat { set { textEdgeInsets.left = newValue } get { return textEdgeInsets.left } } @IBInspectable var paddingRight: CGFloat { set up { textEdgeInsets.correct = newValue } become { return textEdgeInsets.right } } @IBInspectable var paddingTop: CGFloat { gear up { textEdgeInsets.top = newValue } get { render textEdgeInsets.top } } @IBInspectable var paddingBottom: CGFloat { ready { textEdgeInsets.bottom = newValue } get { render textEdgeInsets.lesser } } }
Lawmaking language: Swift ( swift )
Using Padding in UILabel
Storyboard
If you're using storyboards, after you have added the characterization in your view, add the PaddingLabel class as a Custom Class
Next, select the Attribute Inspector and add the padding:
Programmatically
If you accept created an UILabel programmatically, replace the UILabel grade with the PaddingLabel and add the padding:
// Init Label let label = PaddingLabel() characterization.backgroundColor = .black label.textColor = .white label.font = .systemFont(ofSize: 26, weight: .semibold) label.text = "UILabel with Padding" self.view.addSubview(characterization) // Padding characterization.paddingLeft = 15 label.paddingRight = 15 characterization.paddingTop = 8 characterization.paddingBottom = 8 // ...
Code linguistic communication: Swift ( swift )
You lot can observe the final project here
If you have any questions,please feel free to go out a commentbelow
How To Add Padding To Uilabel Swift,
Source: https://johncodeos.com/how-to-add-padding-in-uilabel-in-ios-using-swift/
Posted by: harrisonrondid.blogspot.com
0 Response to "How To Add Padding To Uilabel Swift"
Post a Comment