43

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 to have a translucent effect to fade into the background?

var myField: UITextField = UITextField (frame:CGRectMake(10, 10, 30, 10));
self.addSubview(myField)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3763693
  • 1,375
  • 3
  • 12
  • 11

9 Answers9

94

Swift 3 & Swift 4.2:

override func viewDidLoad() {
    super.viewDidLoad()

    let sampleTextField =  UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
    sampleTextField.placeholder = "Enter text here"
    sampleTextField.font = UIFont.systemFont(ofSize: 15)
    sampleTextField.borderStyle = UITextField.BorderStyle.roundedRect
    sampleTextField.autocorrectionType = UITextAutocorrectionType.no
    sampleTextField.keyboardType = UIKeyboardType.default
    sampleTextField.returnKeyType = UIReturnKeyType.done
    sampleTextField.clearButtonMode = UITextField.ViewMode.whileEditing
    sampleTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
    sampleTextField.delegate = self
    self.view.addSubview(sampleTextField)
}

Delegate Methods:

// MARK:- ---> UITextFieldDelegate

extension ViewController: UITextFieldDelegate {

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        // return NO to disallow editing.
        print("TextField should begin editing method called")
        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        // became first responder
        print("TextField did begin editing method called")
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
        print("TextField should snd editing method called")
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
        print("TextField did end editing method called")
    }

    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        // if implemented, called in place of textFieldDidEndEditing:
        print("TextField did end editing with reason method called")
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // return NO to not change text
        print("While entering the characters this method gets called")
        return true
    }

    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        // called when clear button pressed. return NO to ignore (no notifications)
        print("TextField should clear method called")
        return true
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // called when 'return' key pressed. return NO to ignore.
        print("TextField should return method called")
        // may be useful: textField.resignFirstResponder()
        return true
    }

}

// MARK: UITextFieldDelegate <---

Swift 2.0:

let sampleTextField = UITextField(frame: CGRectMake(20, 100, 300, 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFontOfSize(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
sampleTextField.delegate = self
self.view.addSubview(sampleTextField)

Delegate Methods:

    // MARK:- ---> Textfield Delegates
    func textFieldDidBeginEditing(textField: UITextField) {
        print("TextField did begin editing method called")
    }

    func textFieldDidEndEditing(textField: UITextField) {
        print("TextField did end editing method called")
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("TextField should begin editing method called")
        return true;
    }

    func textFieldShouldClear(textField: UITextField) -> Bool {
        print("TextField should clear method called")
        return true;
    }

    func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        print("TextField should snd editing method called")
        return true;
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        print("While entering the characters this method gets called")
        return true;
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("TextField should return method called")
        textField.resignFirstResponder();
        return true;
    }
    // MARK: Textfield Delegates <---
Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
Ashok
  • 5,585
  • 5
  • 52
  • 80
  • I'm able to create the text field programmatically, but where or how do I create an outlet for this text field? When a button is pressed I need to read the values in this field run some code. – tylerSF Oct 05 '16 at 15:00
  • 3
    Nevermind, i figured it out. As easy as `sampleTextField.text` :) – tylerSF Oct 06 '16 at 13:11
  • How to add multiple text fields programatically?? in loop if have have input – Xcodian Solangi Dec 09 '17 at 10:02
  • @XcodianSolangi Check it here: https://gist.github.com/AshokKumarYes/f064f25787607cca46932fc76555be26 – Ashok Dec 09 '17 at 14:46
14
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

bdash
  • 18,110
  • 1
  • 59
  • 91
Kumar KL
  • 15,315
  • 9
  • 38
  • 60
  • 1
    Also shouldn't it be let rather than var?- you can still change class properties, and it's unlikely to need to be reassigned. – Woodstock Jul 12 '14 at 06:49
10

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
deijmaster
  • 562
  • 5
  • 11
5

You need to add text field to self.view instead of self.

var myField: UITextField = UITextField (frame:CGRectMake(10, 10, 30, 10));
self.view.addSubview(myField) 

For add translucent blur effect there are already a couple of suggestions available, you can go through -

UIView border with fade or blur effect

Community
  • 1
  • 1
rishi
  • 11,779
  • 4
  • 40
  • 59
5

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)
Yalamandarao
  • 3,852
  • 3
  • 20
  • 27
5

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
}()
Sour LeangChhean
  • 7,089
  • 6
  • 37
  • 39
2

Add the textField on UIView is

var textField=UITextField(frame:CGRectMake(x,y,width,height));
self.view.addSubView(textField)
2

Make sure you're in the viewDidLoad() and then simply add the following code to produce a textField:

let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00));
    self.view.addSubview(myTextField)

    myTextField.backgroundColor = UIColor.redColor()
    myTextField.text = "some string"
    myTextField.borderStyle = UITextBorderStyle.Line
Amiru Homushi
  • 139
  • 1
  • 5
2

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)