senty
senty

Reputation: 12857

Centering Horizontally using CGRect and Giving Contraint Programatically

I have a UITextField which is programatically created. I tried to center it using UIScreen.mainScreen().bounds.width / 2 but it doesn't seem right. What is the proper way of aligning ui item using CGRect? How can I center UITextField horizontally?

    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)

I also have another question. I have @IBOutlet weak var label: UILabel! and together as aligning the above UITextField horizontally, I want to give it a constraint too to keep its distance with the UILabel.

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

Upvotes: 0

Views: 1856

Answers (3)

dimpiax
dimpiax

Reputation: 12697

look at CGRect properties:

midX, midY

Upvotes: 0

D. Greg
D. Greg

Reputation: 1000

When you center an object, you also have to consider the width of the object. The position is based on 0x,0y of your textfield. I usually do something like this:

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)

That should get you centered in the view.

Upvotes: 1

AdamPro13
AdamPro13

Reputation: 7400

You problem is that the origin of the view is in the top left corner, not in the center. You want let textFieldFrame = CGRect(x: (screenWidth - 200) / 2, y: (screenHeight - 40) / 2).

Also, I would recommend using the window's size, not the screen size. This can mess you up if you ever decide to support iPad multitasking.

Upvotes: 2

Related Questions