UItextField.text为以编程方式创建的UItextfield返回nil尽管我已经在其中输入了一些文本...

问题描述

新手很快,我确实已经花了4天的时间,并且坚持这一工作,我认为这很简单,对我来说再没有意义了。 当我使用情节提要创建UItextfiled时,来回UItextfield.text

并没有问题。

当像在“ textProjectNumber”下面的示例那样以编程方式创建UItextfiled.text时 那么即使我在urtextfiled中输入了项目编号,并尝试稍后在同一个类中调用该文本,似乎该文本是= nil...。请您帮我了解问题出在哪里。 / p>

 override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
    
    let textProjectNumber = UITextField(frame: CGRect(x: 20,y: 100,width: 300,height: 40))
    textProjectNumber.translatesAutoresizingMaskIntoConstraints = false
    textProjectNumber.placeholder = "Enter text here"
    textProjectNumber.font = UIFont.systemFont(ofSize: 15)
    textProjectNumber.borderStyle = UITextField.BorderStyle.roundedRect
    textProjectNumber.autocorrectionType = UITextAutocorrectionType.no
    textProjectNumber.keyboardType = UIKeyboardType.numberPad
    textProjectNumber.returnKeyType = UIReturnKeyType.done
    textProjectNumber.clearButtonMode = UITextField.ViewMode.whileEditing
    textProjectNumber.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
    textProjectNumber.tag = 1
    textProjectNumber.updateConstraintsIfNeeded()
    textProjectNumber.delegate = self
    
    // add the uitextfield in the view
    
    self.view.addSubview(textProjectNumber)
    
    //add the constrain for this uitextfield
    
    NSLayoutConstraint.activate([
        textProjectNumber.centerXAnchor.constraint(
            equalTo: view.centerXAnchor,constant: 0),textProjectNumber.centerYAnchor.constraint(
            equalTo: view.centerYAnchor,constant: 0)
    ])
    
    textProjectName.translatesAutoresizingMaskIntoConstraints = false
    textProjectName.delegate = self


     // MARK: - Navigation
 
    // Enable the Save button only if the text field has a valid project name.
    
        updateSaveButtonState()
    
}

//MARK: UItextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
    textField.autocorrectionType = .no
    if textField.tag == 2 { // tag 2 = textProjectName tag1 = textProjNumber
        textField.autocorrectionType = .yes
    }
    textField.autocorrectionType = .no
    
    //Hide the keyboard
        textField.resignFirstResponder()
    return true
    
}




func textFieldDidEndEditing(_ textField: UITextField) {
    //update the status of the buttong when we finish editing the uI textfiled
    updateSaveButtonState()

    //add the title of this new project creation with textfiled + PF-
    if textProjectName.text?.isEmpty ?? true {
    navigationItem.title = "PF-" + textProjectName.text! }
    textField.autocorrectionType = .no
    textField.resignFirstResponder()

}

func textFieldDidBeginEditing(_ textField: UITextField) {
    
    // Disable the Save button while editing.
    saveNewProjectButton.isEnabled = false
    createbuttonsinkeyboard(textField)
    if textField.tag == 2 {
        textField.autocorrectionType = .yes
    } else {
        textField.autocorrectionType = .no
    }
}


func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {


    if textField.tag == 1 {


        if range.length + range.location > (textField.text?.count)! {
            return false
        }
        
        
        let newLenght = (textField.text?.count)! + string.count - range.length
        if (textField.text?.contains("PF-"))! {
            textField.text! = textField.text!.replacingOccurrences(of: "PF-",with: "",options: NSString.CompareOptions.literal,range: nil)
            
        }
        print("do i do that")
        return newLenght <= 8
    }

    return true
}



//MARK: Private Methods
private func updateSaveButtonState(){
    

    // Disable the Save button if the text field is empty.

    if textProjectName.text?.isEmpty ?? false || ((textProjectName.text?.isEmpty) != false) {
        saveNewProjectButton.isEnabled = false
    } else {
        saveNewProjectButton.isEnabled = true
    }
}


//MARK: Create object function with keyboard


@objc func Done(){
    
   view.endEditing(true)
        let numbFromUser = textProjectNumber.text
    if activeTextField.tag == 1 {
        textProjectNumber.text = "PF-" + numbFromUser!
   
    }
    print(numbFromUser!)

     
}


@objc func Cancel(){
    self.activeTextField.text = ""
}

//save button function
@IBAction func SaveNewProject() {
    let actionSheet = UIAlertController (title: "WARNING",message: "CREAT A NEW PROJECT WITH THE FOLLOWING INFO:\n\(textProjectNumber.text ?? "Empty") \n\(textProjectNumber.text ?? "Empty")",preferredStyle: .alert)
    let okaction = UIAlertAction(title: "Agree",style: .default) { (action) in
        self.gotoFouthViewController(/*add argument if needed*/)
        
        
    }
    //cancel the alert
    let cancelaction = UIAlertAction(title: "Cancel",style: .cancel) { (action) in
        
    }
    actionSheet.addAction(okaction)
    actionSheet.addAction(cancelaction)
    present(actionSheet,animated: true,completion: nil)
    
    
}
func gotoFouthViewController() {
    //push or present the fourth view controller here
    let home = storyboard?.instantiateViewController(withIdentifier: "homepage") as! ViewController
    // secondVC.statusDelegate = self
    navigationController?.pushViewController(home,animated: true)
}

func createbuttonsinkeyboard(_ textField: UITextField) {

    // self.activeTextField.text is an optional,we safely unwrap it here
   self.activeTextField = textField
        //      // Create a toolbar
        let toolBar = UIToolbar(frame: CGRect(x: 0,y: 0,width: UIScreen.main.bounds.width,height: 40))
        //toolBar.sizeToFit()
      

        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done,target: self,action: #selector(Done))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace,action: nil)
        let emptyButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel,action: #selector(Cancel))

        // Add a toolbar buttons in each textfiled
        textField.inputAccessoryView = toolBar
        toolBar.setItems([emptyButton,spaceButton,doneButton],animated: false)
        toolBar.updateConstraintsIfNeeded()

        return;
      }


  }

this help me to fid constraint auto or not
extension NSLayoutConstraint {

override public var description: String {
    let id = identifier ?? ""
    return "id: \(id),constant: \(constant)" //you may print whatever you want here
     }

 }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)