UILabel 不会在 UIView 中居中

UILabel won't center in UIView

我正在尝试创建一个自定义 UIView,它可以用作进度条或类似的东西(@IBDesignableIBInspectables)。我想要在此视图中居中(主要是 X 轴,但现在 Y 轴)UILabel

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

}

问题是label.center = self.center,因为label的中心点和superview的中心点在不同的坐标系下,可能不一样。改用

label.center = CGPoint(x: self.view.frame.bounds.size.width / 2.0, y:self.view.frame.bounds.size.height / 2.0)

试试这个:

self.label.center = view.center

以编程方式添加 UILabel 并修改来自

的 UILabel 框架
let label = UILabel(frame: CGRectMake(0, 0, self.frame.width / 4, self.frame.height / 4))

let label = UILabel(frame: CGRectMake(self.frame.width/2 - (self.frame.height/4)/2, 0, self.frame.width / 4, self.frame.height / 4))

其他

实施自动布局

一个可能的解决方案是:-

@IBOutlet customView : UIView! 
//Let customView be the outlet of your custom view

func addLabel () {
    let CenterY = customView.center.y
    let CenterX = customView.center.x
    let heightOfCustom = customView.frame.size.height
    let widthOfCustom = customView.frame.size.width
    // If you want a label with height and width 1/4th of the width of the custom view
    let label = UILabel(frame : CGRectMake(CenterX - widthOfCustom/8, CenterY - heightOfCustom/8, widthOfCustom/4, heightOfCustom/4))
    label.text = "5"
    label.textAlignment = .Center
    label.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
    self.addSubview(label)
}