Ich versuche, eine benutzerdefinierte UIView
erstellen, die als Fortschrittsbalken oder ähnliches (@IBDesignable
mit IBInspectable
s) verwendet werden kann. Ich möchte eine zentrierte (hauptsächlich X-Achse, aber jetzt auch Y) UILabel
in dieser Ansicht.UILabel wird nicht zentriert in 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)
}
In Interface die Label-Zentren gerade fein:
Allerdings, wenn es auf meinem Gerät (iPhone 5S) läuft das Etikett leicht nach rechts ausgerichtet ist (Bild unten). Ich habe verschiedene Ansätze ausprobiert (z. B. das Erstellen des Etikettenrahmens self.frame
), aber es ist immer noch nicht richtig zentriert. Was vermisse ich?
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
}
Align UILabel Zentrum durch Autolayouts in Nib/Storyboard-Datei. –