Create UITextField Programmatically

In this short Swift code example, you will learn how to create UITextField in Swift programmatically.

The code example below will cover the following:

  • Create UITextField of specific height and width,
  • Position UITextField at the center of the view,
  • Set UITextField backgroundColor,
  • Set UITextField textColor,
  • Set UITextField UITextBorderStyle,
  • Add UITextField as a subview,
  • Set UITextField placeholder text,
  • Set UITextField sample text.
// Create UITextField
let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));

// Or you can position UITextField in the center of the view
myTextField.center = self.view.center

// Set UITextField placeholder text
myTextField.placeholder = "Place holder text"

// Set text to UItextField
myTextField.text = "UITextField example"

// Set UITextField border style
 myTextField.borderStyle = UITextField.BorderStyle.line

// Set UITextField background colour
myTextField.backgroundColor = UIColor.white

// Set UITextField text color
myTextField.textColor = UIColor.blue


// Add UITextField as a subview
self.view.addSubview(myTextField)

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.