1

I have a label with a rectangular border. I wish to add space between the label's text and the label's border.
I tried following the steps described here: https://stackoverflow.com/a/40385630/9735046

myLabel.frame.size.width = myLabel.intrinsicContentSize.width + 10
myLabel.frame.size.height = myLabel.intrinsicContentSize.height + 10
myLabel.textAlignment = .center

But it did not add space between my label's text and border.
How would I add space?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Karliene
  • 147
  • 1
  • 3
  • 10

3 Answers3

2

The problem is in viewDidLoad frame is not yet to be set so try this

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



    lb.text = "dbjsjdhsjhdshjdshjdshdjs"

    lb.layer.borderColor = UIColor.red.cgColor

    lb.layer.borderWidth = 3

    lb.textAlignment = .center

    view.addSubview(lb)

    lb.sizeToFit()

    lb.center = view.center
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    lb.frame.size.width = lb.intrinsicContentSize.width + 100

    lb.frame.size.height = lb.intrinsicContentSize.height + 100

    lb.center = view.center

}

//

enter image description here

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

Auto-layout is probably overriding your size change. Try adding a size constraint to the label. Note that this is easier in a Storyboard than in code.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
1

See its simple. If you have label width bigger than text and use textalignment as Center then it will work how you want and text will be in center having space at start & end of label. Like below :

enter image description here

If you don't want text-alignment as Center and want to keep text-alignment as left then same will look like below :

enter image description here

So now with left-aligned and you want space between border and text then you have to add white space before actual text value start like below:

    let strValue = "I want Space"
    label?.text = " \(strValue)"

And Result will be this :

enter image description here

So you can see the difference.

Kalpesh Panchasara
  • 1,730
  • 2
  • 15
  • 27