gpt4 book ai didi

swift - 使用 UITextField 和 UITextView 时出错

转载 作者:行者123 更新时间:2023-11-30 10:37:06 24 4
gpt4 key购买 nike

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

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 是一个类,您无法从中获取 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!
}
}

关于swift - 使用 UITextField 和 UITextView 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57736683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com