在 swift 中以编程方式适应 cgsize 的方面

Aspect fit in cgsize programmatically in swift

Click here for image.

需要帮助调整标签以便左右两侧填充。 代码在底部。

  @IBOutlet weak var header: UILabel!

override func viewDidLoad() {
    header.adjustsFontSizeToFitWidth = true

    let rectShape = CAShapeLayer()
    rectShape.bounds = self.header.frame
    rectShape.position = self.header.center
    rectShape.path = UIBezierPath(roundedRect: self.header.bounds, byRoundingCorners: [.bottomLeft , .bottomRight], cornerRadii: CGSize(width:300, height: 200)).cgPath

    self.header.layer.backgroundColor = UIColor.green.cgColor
    //Here I'm masking the textView's layer with rectShape layer
    self.header.layer.mask = rectShape


    super.viewDidLoad()

您可以通过将代码块放入 viewDidAppear(_:) 来解决此问题。在这个方法中,尺寸会被修正。

@IBOutlet weak var header: UILabel!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    header.adjustsFontSizeToFitWidth = true

    let rectShape = CAShapeLayer()
    rectShape.bounds = self.header.frame
    rectShape.position = self.header.center
    rectShape.path = UIBezierPath(roundedRect: self.header.bounds, byRoundingCorners: [.bottomLeft , .bottomRight], cornerRadii: CGSize(width:300, height: 200)).cgPath

    self.header.layer.backgroundColor = UIColor.green.cgColor
    //Here I'm masking the textView's layer with rectShape layer
    self.header.layer.mask = rectShape
}