Oliver Redeyoff
Oliver Redeyoff

Reputation: 197

Center a UITextField

I am trying to center a UITextField and this is my code :

import SpriteKit
import GameplayKit
import UIKit

class GameScene: SKScene {

var sampleTextField = UITextField()

override func didMove(to view: SKView) {

    let mainView = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))

    view.addSubview(mainView)

    sampleTextField = UITextField(frame: CGRect(origin: mainView.center, size: CGSize(width: 200, height: 20)))

    sampleTextField.placeholder = "Enter text here"
    sampleTextField.font = UIFont.systemFont(ofSize: 15)
    sampleTextField.borderStyle = UITextBorderStyle.roundedRect
    sampleTextField.autocorrectionType = UITextAutocorrectionType.no
    sampleTextField.keyboardType = UIKeyboardType.default
    sampleTextField.returnKeyType = UIReturnKeyType.done
    sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
    sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center

    mainView.addSubview(sampleTextField)
    }

}

But the UITextField doesn't appear because I think it is outside of the screen, so how could I center it in the screen?

Upvotes: 1

Views: 227

Answers (2)

Christoph
Christoph

Reputation: 722

Instead of..

sampleTextField = UITextField(frame: CGRect(origin: mainView.center, size: CGSize(width: 200, height: 20)))

do this..

sampleTextField = UITextField(frame: CGRect(origin: CGPoint(x: mainView.center.x - 100, y: mainView.center.y - 10), size: CGSize(width: 200, height: 20)))

The orgin of a CGRect is always on the top left corner. You need to subtract half of the width and height of the center point.

Upvotes: 1

Hussain Shabbir
Hussain Shabbir

Reputation: 14995

Try using center method:-

sampleTextField.center = CGPoint(x: value1, y: value2)

Upvotes: 1

Related Questions