Ios UILabel赢得';UIView中的t中心

Ios UILabel赢得';UIView中的t中心,ios,swift,uiview,uilabel,drawrect,Ios,Swift,Uiview,Uilabel,Drawrect,我正在尝试创建一个自定义的ui视图,它可以用作进度条或类似的(@IBDesignable,带有IBInspectables)。在这个视图中,我想要一个居中的(主要是X轴,但现在也是Y轴)UILabel private func addLabel() { let label = UILabel(frame: CGRectMake(0, 0, self.frame.width / 4, self.frame.height / 4)) label.center = self.cente

我正在尝试创建一个自定义的
ui视图
,它可以用作进度条或类似的(
@IBDesignable
,带有
IBInspectable
s)。在这个视图中,我想要一个居中的(主要是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
),但仍然没有正确居中。我错过了什么


问题是
label.center=self.center
,因为标签的中心和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))

其他


实施自动布局

可能的解决方案是:-

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

通过Nib/故事板文件中的自动布局对齐UILabel Center。感谢您的解释和解决方案!
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)
}