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)

9 Answers 9

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 <---
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Nevermind, i figured it out. As easy as sampleTextField.text :)
How to add multiple text fields programatically?? in loop if have have input
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

1 Comment

Also shouldn't it be let rather than var?- you can still change class properties, and it's unlikely to need to be reassigned.
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

Comments

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

Comments

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)

Comments

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
}()

Comments

2

Add the textField on UIView is

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

Comments

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.