我正在嘗試創建可用作進度欄或類似的自定義UIView
(@IBDesignable
和IBInspectable
s)。我想在這個視圖中居中(主要是X軸,但現在也是Y)UILabel
。UILabel將不會在UIView中心
private func addLabel()
{
let label = UILabel(frame: CGRectMake(0, 0, self.frame.width/4, self.frame.height/4))
label.center = self.center
label.textAlignment = .Center
label.text = "5"
//Color just to see the whole label
label.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
self.addSubview(label)
}
InterfaceBuilder下的標籤中心就好了:
然而,我的設備上運行時,它(iPhone 5S)標籤稍微向右排列(如下圖所示)。我嘗試過不同的方法(如製作標籤框架self.frame
),但它仍然沒有正確居中。我錯過了什麼?
override func drawRect(rect: CGRect) {
// Drawing code
let center = CGPoint(x:bounds.width/2, y: bounds.height)
let radius: CGFloat = max(bounds.width, bounds.height)
let startAngle: CGFloat = π
let endAngle: CGFloat = 2 * π
path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.lineWidth = arcWidth
arcBackgroundColor.setStroke()
path.stroke()
self.addLayer()
}
private func addLayer()
{
progressLayer = CAShapeLayer()
progressLayer.path = self.path.CGPath
progressLayer.strokeColor = self.progressColor.CGColor
progressLayer.fillColor = UIColor.clearColor().CGColor
progressLayer.lineWidth = self.arcWidth
if animatesOnDraw && progress > 0 {
self.layer.addSublayer(progressLayer)
self.animateProgress(0)
} else {
progressLayer.strokeEnd = CGFloat(self.progress/self.maxValue)
progressLayer.opacity = Float(self.progressStrokeEndValue)
self.layer.addSublayer(progressLayer)
}
addLabel() //as shown above
}
通過自動版式對齊的UILabel中心在筆尖/故事板文件。 –