我正在尝试创建可用作进度栏或类似的自定义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中心在笔尖/故事板文件。 –