【问题标题】:Errors using UITextField and UITextView使用 UITextField 和 UITextView 的错误
【发布时间】:2019-08-31 09:17:35
【问题描述】:

我正在向我的 Xcode 项目添加一个在文本视图中显示文本的文本字段。我已经完成了大部分工作的编码,但它抛出了两个错误。第一个是

无法分配“(UITextField) -> (UITextRange) -> String?”类型的值?输入'字符串?

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

二元运算符“+=”不能应用于“字符串?”类型的操作数和'(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
    }
}

【问题讨论】:

    标签: swift xcode uibutton uitextfield uitextview


    【解决方案1】:

    您将textFieldUITextField 打错了。 UITextField 是一个类,您无法从中获取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!
        }
    }
    

    【讨论】:

    • 解开 mText 以及 textView.text! += mText!
    • 鹰眼。谢谢@Kamran
    猜你喜欢
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多