gpt4 book ai didi

ios - 使用 CGRect 水平居中并以编程方式提供约束

转载 作者:行者123 更新时间:2023-11-28 11:09:31 31 4
gpt4 key购买 nike

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

最佳答案

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

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

关于ios - 使用 CGRect 水平居中并以编程方式提供约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999771/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com