使用Swift编程,在UIView上以编程方式添加UITextField

43

我刚开始学习Swift和iOS编程。我试着用Swift编写代码来创建一个UITextField,但是一直无法完美实现。还有,请问如何将其设置为半透明的效果以便融入背景?

var myField: UITextField = UITextField (frame:CGRectMake(10, 10, 30, 10));
self.addSubview(myField)
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)
}

委托方法:

// 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)

委托方法:

    // 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 <---

我能够通过编程创建文本字段,但是我应该在哪里或如何为此文本字段创建一个插座呢?当按下按钮时,我需要读取此字段中的值并运行一些代码。 - tylerSF
3
没关系,我想清楚了。跟 sampleTextField.text 一样容易 :) - tylerSF
如何编程添加多个文本字段?如果有输入,可以在循环中进行。 - Xcodian Solangi
@XcodianSolangi 在这里查看:https://gist.github.com/AshokKumarYes/f064f25787607cca46932fc76555be26 - Ashok

14
self.addSubview(myTextField)

只有在使用 UIView 的子类时才能起作用。

您必须将其作为ViewController层次结构中的UIView的子视图添加。

var txtField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 500.00, height: 30.00));
self.view.addSubview(txtField)

默认情况下,背景色为白色,但可能不会显示。您需要同时提供样式、文本颜色和背景颜色。

txtField.borderStyle = UITextBorderStyle.Line
txtField.text = "myString" 
txtField.backgroundColor = UIColor.redColor()

了解更多信息,请点击这里


1
还有,应该用let而不是var吧?你仍然可以更改类属性,而且不太可能需要重新分配。 - Woodstock

10

已更新至 Swift 3 和 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

5

请尝试以下代码:

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)

5

您需要将文本字段添加到self.view而不是self

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

要添加半透明模糊效果,已经有一些建议可供参考,您可以查看以下链接:

UIView边框带渐变或模糊效果


5
您可以使用以下代码与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
}()

2
在UIView上添加textField是这样的:
var textField=UITextField(frame:CGRectMake(x,y,width,height));
self.view.addSubView(textField)

2

viewDidLoad() 中编写代码并实现代理 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)

2

请确保您位于viewDidLoad()中,然后只需添加以下代码即可生成一个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接