让文字更多地朝着UILabel的中间开始?

时间:2016-11-23 00:04:01

标签: ios swift

我以编程方式制作了一个带背景色的UILabel,目前看起来像这样:

label

我不喜欢文字如何接近其背景颜色的左右边缘,是否有任何方法可以使它更接近中间,所以它看起来像这样: / p>

optimal 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

2 个答案:

答案 0 :(得分:1)

您可以尝试添加容器视图,根据需要设置背景颜色,然后在其上添加没有背景颜色的标签。

答案 1 :(得分:1)

你可能需要在widthAnchors上玩一下,但试试这个:

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