我的快速应用程序中有一些应该有边框的标签。我在标签上添加了边框,但我想在标签和边框之间留出更多空格。
我该怎么做?
答案 0 :(得分:5)
一个简单的解决方案是将标签嵌入视图中,然后将边框添加到此视图,而不是标签本身。我希望这能帮到你。
答案 1 :(得分:4)
试试这个:
myLabel.frame.size.width = myLabel.intrinsicContentSize.width + 10
myLabel.frame.size.height = myLabel.intrinsicContentSize.height + 10
myLabel.textAlignment = .center
答案 2 :(得分:0)
我这样做了(将文本放在同一位置)
//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
答案 3 :(得分:0)
1.添加这个类
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.将标签的类别更改为 PaddingLabel
3.将此代码添加到您的 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)
}
}