我正在尝试以编程方式在我使用 Open Source software
创建的循环加载图像中添加label
。我面临的问题是我不知道如何constrain
标签,使其包含在圆圈内。我正在尝试将CAShapeLayer
与UILabel
进行比较,但这不起作用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))
}
迅速:
override func layoutSubviews() {
super.layoutSubviews()
statusLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidX(self.bounds))
}