2016-01-13 69 views
0

我正在嘗試在程序中在使用Open Source software創建的循環加載圖像中添加一個label。我面臨的問題是我不知道如何標籤,使其包含在圓圈內。我試圖將CAShapeLayerUILabel進行比較,但這不會起作用,因爲CAShapeLayer不是可從Storyboard獲得的類型。有沒有我應該遵循的建議修復?以編程方式爲UILabel添加一個圓形加載動畫的約束

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

回答

1

刪除此代碼:

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) 

添加以下代碼:

Objectice 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)) 
} 
+0

做喲你有這個Swift版本嗎? –

+0

用Swift Code更新。 –

相關問題