Search code examples
iosconstraintsaddsubviewprogrammatically-created

Programmatically adding constraints for a UILabel for a circular load animation


I am trying to add a label programmatically inside a circular loading image that I created using Open Source software. The problem I am facing is that I do not know how to constrain the label such that it is contained within the circle. I am trying to compare a CAShapeLayer to a UILabel, but this isn't going to work because CAShapeLayer is not a type available from Storyboard. Is there a suggested fix I should follow?

let circlePathLayer = CAShapeLayer()
var circleRadius: CGFloat = 100.0   
var circleCenter: CGPoint = CGPoint()

func displayStatus() {
    let statusLabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
    statusLabel.center = CGPointMake(160, 284)
    statusLabel.textAlignment = NSTextAlignment.Center
    statusLabel.textColor = UIColor.whiteColor()
    statusLabel.text = "(Up)loading"

    let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR 
    self.addConstraint(horizontalConstraint) 

    let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
    self.addConstraint(verticalConstraint)

    self.addSubview(statusLabel)
}

Solution

  • Remove this Code:

        let horizontalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) //ERROR 
    self.addConstraint(horizontalConstraint) 
    
    let verticalConstraint = NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: circlePathLayer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) //ERROR
    self.addConstraint(verticalConstraint)
    

    Add this Code:

    Objectice C:

    - (void)layoutSubviews
    {
        [super layoutSubviews];
        statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
    }
    

    Swift:

        override func layoutSubviews() {
        super.layoutSubviews()
        statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidX(self.bounds))
    }