0

I've made a UILabel with a background color programmatically which currently looks like this:

label

I don't like how the text is so close to the left and right margins of its background color, is there any way to make it start more towards the middle so it'd look like this:

optimal label

This is how I'm making the label:

        let label = UILabel()
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant:0).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant:0).isActive = true
        label.widthAnchor.constraint(equalToConstant: self.view.frame.width - 30.0).isActive = true
        label.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
        label.numberOfLines = 0
        label.layer.cornerRadius = 10.0
        label.clipsToBounds = true
        label.textAlignment = .center
        label.backgroundColor = UIColor.darkGray
        label.textColor = UIColor.white
MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • Lots of answers to this one here: http://stackoverflow.com/questions/3476646/uilabel-text-margin and also here: http://stackoverflow.com/questions/27459746/adding-space-padding-to-a-uilabel-swift – Son of a Beach Nov 23 '16 at 02:32

2 Answers2

1

You can try adding a container view, set it's background color as you like and then add a label over it with no background color.

Kushal Jogi
  • 265
  • 5
  • 15
1

You may have to play around a bit on the widthAnchors, but try this:

let outerView = UIView()
outerView.backgroundColor = UIColor.darkGray
outerView.translatesAutoresizingMaskIntoConstraints = false
outerView.layer.cornerRadius = 10.0
outerView.clipsToBounds = true
let innerView = UILabel()
innerView.numberOfLines = 0
innerView.textAlignment = .center
innerView.textColor = UIColor.white
innerView.text = "Use 10% less energy this month than the last one"
innerView.translatesAutoresizingMaskIntoConstraints = false
outerView.addSubview(innerView)
view.addSubview(outerView)
outerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
outerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
outerView.widthAnchor.constraint(equalToConstant: self.view.frame.width - 40.0).isActive = true
outerView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
innerView.centerXAnchor.constraint(equalTo: outerView.centerXAnchor).isActive = true
innerView.centerYAnchor.constraint(equalTo: outerView.centerYAnchor).isActive = true
innerView.widthAnchor.constraint(equalTo: outerView.widthAnchor, constant: -100.0).isActive = true