使用 UITextField 和 UITextView 的错误

Errors using UITextField and UITextView

我正在向我的 Xcode 项目添加一个在文本视图中显示文本的文本字段。我已经掌握了大部分代码,但它会返回两个错误。第一个是

Cannot assign value of type '(UITextField) -> (UITextRange) -> String?' to type 'String?

这是在 textView.text = mText 之后的输入按钮功能。第二个错误是

Binary operator '+=' cannot be applied to operands of type 'String?' and '(UITextField) -> (UITextRange) -> String?'

textView.text += mText 行之后。如何解决这些问题?

import UIKit

class ShowGratitudeViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var textView: UITextView!

    @IBAction func enterTextButton(_ sender: Any) {

        //gets text from text field
        let mText = UITextField.text

        //update previous text of textview
        textView.text = mText
    }

    @IBAction func editTextButton(_ sender: Any) {

        //gets text from text field
        let mText = UITextField.text

        //add text after previous text
        textView.text += mText
    }
}

您将 textFieldUITextField 打错了。 UITextField 是一个 class,您无法从中获取 textField 对象的文本。

您遇到的另一个错误是 += 无法应用于可选值和非可选值。所以在应用这个运算符之前打开它。

所以代码应该是这样的:

class ShowGratitudeViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var textView: UITextView!

    @IBAction func enterTextButton(_ sender: Any) {

        //gets text from text field
        let mText = textField.text

        //update previous text of textview
        textView.text = mText
    }

    @IBAction func editTextButton(_ sender: Any) {

        //gets text from text field
        let mText = textField.text

        //add text after previous text
        textView.text! += mText!
    }
}