【问题标题】:Adding UITextField on UIView Programmatically Swift以编程方式在 UIView 上添加 UITextField Swift
【发布时间】:2014-07-12 05:45:58
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift


    【解决方案1】:

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

    【讨论】:

    • 我能够以编程方式创建文本字段,但是我在哪里或如何为这个文本字段创建一个出口?当按下按钮时,我需要读取此字段中的值运行一些代码。
    • 没关系,我想通了。就像sampleTextField.text 一样简单:)
    • 如何以编程方式添加多个文本字段?如果有输入则在循环中
    【解决方案2】:
    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()
    

    欲了解更多信息,here

    【讨论】:

    • 也不应该是 let 而不是 var 吗?- 你仍然可以更改类属性,而且不太可能需要重新分配。
    【解决方案3】:

    为 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
    

    【讨论】:

      【解决方案4】:

      试试下面的代码

      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】:

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

        【讨论】:

          【解决方案6】:

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

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

          关于添加半透明模糊效果已经有一些建议,你可以通过 -

          UIView border with fade or blur effect

          【讨论】:

            【解决方案7】:

            在 UIView 上添加 textField 是

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

            【讨论】:

              【解决方案8】:

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

              【讨论】:

                【解决方案9】:

                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)
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-09-27
                  • 2017-07-02
                  • 1970-01-01
                  • 2017-03-17
                  • 2013-04-08
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多