【问题标题】:Centering Horizontally using CGRect and Giving Contraint Programatically使用 CGRect 水平居中并以编程方式给予约束
【发布时间】:2016-06-30 05:07:20
【问题描述】:

我有一个以编程方式创建的 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      |

【问题讨论】:

    标签: ios xcode swift uiview storyboard


    【解决方案1】:

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

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

    【讨论】:

    • 这是一个 Swift 的事情。您需要将30 转换为CGFloat,如下所示:CGFloat(30)。
    【解决方案2】:

    将对象居中时,还必须考虑对象的宽度。该位置基于您的文本字段的 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)
    

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

    【讨论】:

      【解决方案3】:

      查看 CGRect 属性:

      midX,midY

      【讨论】:

        猜你喜欢
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 2018-11-25
        相关资源
        最近更新 更多