ios 以编程方式在 UIView 上添加 UITextField Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24710041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:21:17  来源:igfitidea点击:

Adding UITextField on UIView Programmatically Swift

iosswift

提问by user3763693

I'm new to Swift and iOS programming. I was trying to create a UITextFieldprogrammatically 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?

我是 Swift 和 iOS 编程的新手。我试图UITextField使用 Swift以编程方式创建一个,但无法完全正确。另外你如何改变它以具有半透明效果以淡入背景?

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

回答by Ashok

Swift 3 & Swift 4.2:

斯威夫特 3 和斯威夫特 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:

斯威夫特 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 <---

回答by Kumar KL

self.addSubview(myTextField)

Could work only, if you're working with the subclass of UIView.

仅当您使用UIView.

You have to add it as a subview of the UIView of the ViewController's hierarchy.

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

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

欲了解更多信息,请点击此处

回答by deijmaster

Updated for Swift 3 and Xcode 8.2

为 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

回答by Yalamandarao

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)

回答by rishi

You need to add text field to self.viewinstead of self.

您需要将文本字段添加到self.view而不是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

带有淡入淡出或模糊效果的 UIView 边框

回答by Davina Arnold

Write the code in viewDidLoad()and implement delegate UITextFieldDelegate

编写代码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)

回答by Mahendra Vishwakarma

Add the textField on UIView is

在 UIView 上添加 textField 是

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

回答by Amiru Homushi

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

确保您在 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

回答by Sour LeangChhean

You can use below code with Swift 5.2:

您可以在 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
}()