为 UILabel 创建插图 Space

creating inset Space for UILabel

任何人都知道如何从 UIlabel 中的每个方向获取 Inset 间隙

我这样做了,但它只给我右侧和上方(从 X 和 Y 坐标)的间隙

 class LabelClass: UILabel {

override func drawTextInRect(rect: CGRect) {
    let newRect = CGRectOffset(rect, 10, 0) // move text 10 points to the right
    super.drawTextInRect(newRect)
}

}

如果有人知道如何得到那个插图 space 那么请告诉我,如果 我的问题无法理解,请让我知道我会解决这个问题,谢谢 :)

如果你想在 UILabel 的每一边插入一个间距,你可以简单地 re-set 它的框架,通过改变每个组件

插入 space
let frame: CGRect = myLabel.frame
let myOffset: CGFloat = 4 //set this to whatever you want

myLabel.frame = CGRectMake(
    frame.minX - myOffset, //subtract offset from the original X (minX)
    frame.minY - myOffset, //subtract offset from the original Y (minY)
    frame.width + (myOffset * 2), //add offset * 2 to the original width
    frame.height + (myOffset * 2) //add offset * 2 to the original height
)

例如,如果偏移量是一个

 Subtracted one from the original x position (frame.minX)
 |
 |        Added (1 * 2) = two to the original width (frame.width)
 |        ||
 v        vv

 >+++++++++<   <- Subtracted one from the original y position (frame.minY)
 >         <
 >  Label  <
 >         <   <-
 >+++++++++<   <- Added (1 * 2) = two to the original height (frame.height)

  >+++++++<
  > Label <
  >+++++++<

文本保留在同一位置,但更改了框架以添加所需的间距

另一方面,如果你想从superview中添加padding,你只需要反转上面代码中的符号

let frame: CGRect = myLabel.frame
let myOffset: CGFloat = 4 //set this to whatever you want

myLabel.frame = CGRectMake(
    frame.minX + myOffset, //subtract offset from the original X (minX)
    frame.minY + myOffset, //subtract offset from the original Y (minY)
    frame.width - (myOffset * 2), //add offset * 2 to the original width
    frame.height - (myOffset * 2) //add offset * 2 to the original height
)

我认为您应该在 UIlabel 的背景中使用一个视图,并使其背景与您的 uilabel 的背景相同

 theLabel.backgroundColor = UIColor(patternImage: UIImage(named: "blah")!) 

像这样