Reputation: 1550
I have in my swift application some labels that should have border. I added border to my label but I want to have more spaces between the label and its border.
How can I do that?
Upvotes: 7
Views: 7241
Reputation: 201
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. change the class of your label to PaddingLabel
3. Add this code to your ViewController
import UIKit
class LabelViewController: UIViewController {
@IBOutlet weak var label: PaddingLabel!
override func viewDidLoad() {
super.viewDidLoad()
//Setting the border
label.layer.borderWidth = 1
label.layer.borderColor = UIColor.blue.cgColor
//Setting the round (optional)
label.layer.masksToBounds = true
label.layer.cornerRadius = label.frame.height / 2
//Setting the padding label
label.edgeInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
}
Upvotes: 2
Reputation: 39
I did this (to get the text on the same place):
//label position
myLabel.layer.frame.size.width += 10
myLabel.layer.frame.origin.x -= 5
myLabel.textAlignment = .center
//border
myLabel.layer.borderColor = UIColor.systemTeal.cgColor
myLabel.layer.borderWidth = 1.0
label.layer.cornerRadius = 8.0
Upvotes: 0
Reputation: 1936
A simple solution would be to embed your label inside a view, and then add the border to this view, instead of to the label itself. I hope this help you.
Upvotes: 5
Reputation: 2660
Try this:
myLabel.frame.size.width = myLabel.intrinsicContentSize.width + 10
myLabel.frame.size.height = myLabel.intrinsicContentSize.height + 10
myLabel.textAlignment = .center
Upvotes: 5