以编程方式使用CGRect水平居中并给出Contraint

时间:2016-03-14 23:08:40

标签: ios xcode swift uiview storyboard

我有一个以编程方式创建的UITextField。我尝试使用UIScreen.mainScreen().bounds.width / 2将其居中,但似乎并不正确。使用CGRect对齐ui项目的正确方法是什么?如何水平居中UITextField?

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    let textFieldFrame = CGRect(x: screenWidth / 2, y: screenHeight / 2, width: 200.00, height: 40.00)

    let textField = HoshiTextField(frame: textFieldFrame)
    textField.placeholderColor = UIColor.whiteColor()
    textField.borderActiveColor = UIColor.whiteColor()

    self.view.addSubview(textField)

我还有另一个问题。我有@IBOutlet weak var label: UILabel!和水平对齐上面的UITextField,我想给它一个约束,以保持与UILabel的距离。

              |        --Label--       |
              |            |           |      I want to center UITextfield
              |            | 20px      |   horizontally and give it a constraint
              |            |           |   to stay 20px below Label 
              |       UITextField      |

3 个答案:

答案 0 :(得分:2)

问题是视图的原点位于左上角,而不是中心。你想要let textFieldFrame = CGRect(x: (screenWidth - 200) / 2, y: (screenHeight - 40) / 2)

另外,我建议使用窗口的大小,而不是屏幕大小。如果您决定支持iPad多任务处理,这可能会让您感到困惑。

答案 1 :(得分:1)

当您居中对象时,您还必须考虑对象的宽度。该位置基于文本字段的0x,0y。我通常做这样的事情:

let frameWidth: CGFloat  = 200.0
let frameHeight:CGFloat  = 40.0

textField.frame = CGRectMake((view.bounds.width / 2) - (frameWidth / 2), 
                  (view.bounds.height / 2) - (frameHeight / 2),
                  frameWidth, frameHeight)

这应该让你在视图中居中。

答案 2 :(得分:0)

查看CGRect属性:

  

midX,midY