首页 > 解决方案 > 为什么 UITextFIeld 在 Swift 中返回可选值?

问题描述

我使用 aUITextField输入数字,但是当我输入第一个数字时,它最终会打印nil。然后,当我输入其他数字时,它会打印出我输入的数字,但optional返回类型。为什么会这样?

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

    //convert string into number
    let input = (numberLabel.text! as NSString).integerValue

    //find answer to label when added by 1111
    let answer = input + 1111
    print(answer)

    let numberText = Int(numberField.text!)
    print("This is number text: \(numberText)

    if answer == numberText {
        print("correct")
        //if user gets answer correct
    } else {
        //if user gets answer incorrect
    }
}

标签: swiftuitextfieldoptional

解决方案


原因可能是因为您使用shouldChangeCharactersInwhich 直到第二个字符才表示字符的变化。理想情况下,您希望用户在完成答案并提交后收到正确答案的通知,在这种情况下,您需要使用以下内容textFieldDidEndEditing

class MyVC: UIViewController, UITextFieldDelegate {
    let textField = UITextField()
    var numberLabel: UILabel {
        let label = UILabel()
        label.text = "100"
        return label
    }
    let button = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(textField)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            textField.widthAnchor.constraint(equalToConstant: 200),
            textField.heightAnchor.constraint(equalToConstant: 100)
        ])
        textField.delegate = self
        
        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        button.tag = 1
        button.backgroundColor = .black
        button.setTitle("Answer", for: .normal)
        self.view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.leadingAnchor.constraint(equalTo: textField.trailingAnchor),
            button.widthAnchor.constraint(equalToConstant: 200),
            button.heightAnchor.constraint(equalToConstant: 100)
        ])
        
    }
    
    @objc func buttonPressed(_ sender: UIButton!) {
        if case let tag = sender.tag, tag == 1 {
            textField.resignFirstResponder()
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        //convert string into number
        let input = (numberLabel.text! as NSString).integerValue
        
        //find answer to label when added by 1111
        let answer = input + 1111
                print(answer)
        
        if let numberText = Int(textField.text ?? "0") {
            print("This is number text: \(numberText)")
            
            if answer == numberText {
                //if user gets answer correct
                print("correct")
            } else {
                //if user gets answer incorrect
                print("wrong")
            }
        }
    }

}

推荐阅读