为UILabel创建插入空间

时间:2016-01-03 06:33:27

标签: swift 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)
}

}

如果有人知道如何获得那个插入空间那么请告诉我,如果  我的问题是不可理解的,请让我知道我会解决这个问题,谢谢:)

2 个答案:

答案 0 :(得分:1)

如果你想在UILabel的每一边插入一个间距,你可以简单地重新设置它的框架,通过改变每个组件插入空格

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
)

答案 1 :(得分:-2)

我认为您应该在UIlabel的背景中使用View,并使其背景与您的uilabel的bg相同

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

类似这样的事情