【问题标题】:UILabel Position different than expectedUILabel 位置与预期不同
【发布时间】:2014-11-17 13:06:54
【问题描述】:

我开始涉足 swift 并遇到了一种奇怪的行为,我想知道是否有人可以解释为什么。我试图将 UILabel 添加到 UIView 并将其放置在 UIView 的中心。理论上这可以通过以下方式实现。

    self.titleContainer = UIView(frame: CGRect(x: self.view.bounds.origin.x, y: self.view.bounds.origin.y
        + 20.0, width: self.view.bounds.width, height: (self.view.bounds.height * cSixth) - 20.0))
    self.titleContainer.backgroundColor = UIColor.blackColor()
    self.view.addSubview(titleContainer)

    self.titleLabel = UILabel()
    self.titleLabel.text = "Naughts and Crosses"
    self.titleLabel.textColor = UIColor.whiteColor()
    self.titleLabel.font = UIFont(name: "Helvetica", size: 10)
    self.titleLabel.sizeToFit()
    self.titleLabel.center = titleContainer.center
    titleContainer.addSubview(self.titleLabel)

然而,这似乎并没有占据上边距。然而,下一段代码工作并将标签定位在中心。

    self.titleContainer = UIView(frame: CGRect(x: self.view.bounds.origin.x, y: self.view.bounds.origin.y
                + 20.0, width: self.view.bounds.width, height: (self.view.bounds.height * cSixth) - 20.0))
    self.titleContainer.backgroundColor = UIColor.blackColor()
    self.view.addSubview(titleContainer)

    self.titleLabel = UILabel()
    self.titleLabel.text = "Naughts and Crosses"
    self.titleLabel.textColor = UIColor.whiteColor()
    self.titleLabel.font = UIFont(name: "Helvetica", size: 10)
    self.titleLabel.sizeToFit()
    self.titleLabel.center = CGPointMake(titleContainer.bounds.midX, titleContainer.bounds.midY)
    titleContainer.addSubview(self.titleLabel)

有什么想法吗?

谢谢 亚历克

【问题讨论】:

    标签: ios iphone swift ios8 uilabel


    【解决方案1】:

    我认为您正在混合坐标系。 self.titleLabel.center 是titleContainer 内部的一个点,titleContainer.center 是[titleContainer superview] 内部的一个点。

    View Programming Guide -> View and Window Architecture -> View Geometry and Coordinate Systems -> 中解释了差异>框架、边界和中心属性的关系。

    【讨论】:

    • 感谢您的回复。我希望标签位于[titleContainer superview] 的中心点,这样肯定有效吗?抱歉,我真的看不出有什么不同?
    • 我添加了一个链接,试图解释这些差异。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多