Search code examples
swiftxcodeuilabelcgrectcgsize

Aspect fit in cgsize programmatically in swift


Click here for image.

Need help fitting label so that the left and right side fills. Code is at the bottom.

  @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()

Solution

  • You can solve this issue by put the code block into the viewDidAppear(_:). In this method, the size will be corrected.

    @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
    }