如何在IOS中制作带有圆形边框的填充UILabel
Posted
技术标签:
【中文标题】如何在IOS中制作带有圆形边框的填充UILabel【英文标题】:How can I make a padded UILabel with rounded border in IOS 【发布时间】:2021-07-22 20:34:40 【问题描述】:我在这里找到了构建填充标签的解决方案 https://***.com/a/58876988/826946 并在此处看到了一个使用 IBInspectable 使其易于从 InterfaceBuilder 中使用的答案:https://***.com/a/32368958/826946。我还希望同一个类能够在一个包中指定边框(宽度、颜色和角半径)。
【问题讨论】:
【参考方案1】:我正在这里建立一个填充标签的解决方案,在这里找到: https://***.com/a/58876988/826946 以及此处找到的 IBInspectable 的使用:https://***.com/a/32368958/826946,最后是此处的边框内容:https://***.com/a/50364841/826946 请注意,背景颜色仍然可以按照您已经可以在 Interface Builder 中为标签设置的常规方式设置
import UIKit
@IBDesignable class PaddedAndBorderedLabel: UILabel
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
@IBInspectable var borderColor : UIColor = UIColor.black
@IBInspectable var borderWidth : CGFloat = 1
@IBInspectable var cornerRadius : CGFloat = 5
override func drawText(in rect: CGRect)
let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
override var intrinsicContentSize: CGSize
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
override func textRect(forBounds bounds:CGRect,
limitedToNumberOfLines n:Int) -> CGRect
let b = bounds
let UIEI = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
let tr = b.inset(by: UIEI)
let ctr = super.textRect(forBounds: tr, limitedToNumberOfLines: 0)
// that line of code MUST be LAST in this function, NOT first
return ctr
override func draw(_ rect: CGRect)
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
super.draw(rect)
【讨论】:
以上是关于如何在IOS中制作带有圆形边框的填充UILabel的主要内容,如果未能解决你的问题,请参考以下文章