I\'m new to Swift and iOS programming. I was trying to create a UITextField
programmatically using Swift but couldn\'t get it quite right. Also how do you change it
Try below code
var textFiled = UITextField(frame: CGRectMake(20.0, 30.0, 100.0, 33.0))
textFiled.backgroundColor = UIColor.redColor()
textFiled.borderStyle = UITextBorderStyle.Line
self.view.addSubview(textFiled)
self.addSubview(myTextField)
Could work only, if you're working with the subclass of UIView
.
You have to add it as a subview of the UIView of the ViewController's hierarchy.
var txtField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 500.00, height: 30.00));
self.view.addSubview(txtField)
By default background colour is white, it just might not appear. You need to provide the style as well as text colour and background colour.
txtField.borderStyle = UITextBorderStyle.Line
txtField.text = "myString"
txtField.backgroundColor = UIColor.redColor()
For more info, here
You can use below code with Swift 5.2:
lazy var titleTextField:UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.placeholder = "Title *"
textField.keyboardType = UIKeyboardType.default
textField.returnKeyType = UIReturnKeyType.done
textField.autocorrectionType = UITextAutocorrectionType.no
textField.font = UIFont.systemFont(ofSize: 13)
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.clearButtonMode = UITextField.ViewMode.whileEditing;
textField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
return textField
}()
Add the textField on UIView is
var textField=UITextField(frame:CGRectMake(x,y,width,height));
self.view.addSubView(textField)
Write the code in viewDidLoad()
and implement delegate UITextFieldDelegate
let _textField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00))
_textField.backgroundColor = UIColor.redColor()
_textField.text = "some string"
_textField.delegate = self
_textField.borderStyle = UITextBorderStyle.Line
self.view.addSubview(_textField)
Updated for Swift 3 and Xcode 8.2
let stepsTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
stepsTextField.placeholder = "Enter text here"
stepsTextField.font = UIFont.systemFont(ofSize: 15)
stepsTextField.borderStyle = UITextBorderStyle.roundedRect
stepsTextField.autocorrectionType = UITextAutocorrectionType.no
stepsTextField.keyboardType = UIKeyboardType.default
stepsTextField.returnKeyType = UIReturnKeyType.done
stepsTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
stepsTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center