Learning Swift & Xcode - @IBAction func reset for display if UITextField is empty

时间:2017-04-12 05:18:10

标签: swift xcode xcode8

Disclaimer: I am teaching myself Swift & Xcode so my question is rather simple.

I'm building a simple application to get started, which has a text field connected to a String output.

The lesson I'm on currently has an excerpt which reads:

"The reset method simply needs to clear out the text of both the nameField and the lyricsView—you can do this by setting each of their text properties to an empty string."

I understand this probably involves an if statement, but I think the explanation on this is rather poor.

Here's the viewcontroller:

class ViewController: UIViewController {

@IBOutlet weak var nameField: UITextField!

@IBOutlet weak var lyricsView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func reset(_ sender: Any) {
}

@IBAction func displayLyrics(_ sender: Any) {
}

}

Can someone explain what they mean by setting the properties of nameField and lyricsView to an empty string in order to reset?

Thanks!

4 个答案:

答案 0 :(得分:1)

如果要清除textField或textView的文本,只需将text属性设置为空字符串即可。正如你的课程暗示:

  

重置方法只需要清除两者的文本   nameField和lyricsView-您可以通过设置它们的每一个来完成此操作   文本属性为空字符串。

重置方法应该是这样的:

@IBAction func reset(_ sender: Any) {
    nameField.text = ""
    lyricsView.text = ""
}

答案 1 :(得分:0)

将此方法添加到重置方法以删除内容: -

 nameField.text = ""
 lyricsView.text = ""

答案 2 :(得分:0)

当您在nameField中输入内容时,lyricsView中会显示某些内容。因此,应该有一种方法可以清除您输入的内容(以及显示的内容)。因此,重置功能(我猜它被绑定到一个按钮)。

点击重置后,nameFieldlyricsView中的文字就会消失。您可以通过将两者分配给名为空字符串的内容来完成此操作,这只是两个双引号:

let anEmptyString = ""

您需要将""分配给nameFieldlyricsView文字属性。

答案 3 :(得分:0)

要清除我使用的字段:

@IBAction func reset(_ sender: Any) {
    nameField?.text = ""
    lyricsView?.text = ""
}

即使由于某些原因,这些字段尚未加载,或已被释放或删除,问号也将安全地执行代码。