以编程方式为循环加载动画的 UILabel 添加约束

Programmatically adding constraints for a UILabel for a circular load animation

我正在尝试以编程方式在我使用 Open Source software 创建的圆形加载图像中添加一个 label。我面临的问题是我不知道如何 constrain 标签以使其包含在圆圈内。我正在尝试比较 CAShapeLayerUILabel,但这行不通,因为 CAShapeLayer 不是 Storyboard 可用的类型。是否有我应该遵循的建议修复方法?

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

删除此代码:

    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)

添加此代码:

目标 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))
}