【问题标题】:Add string to a string from users input Swift ( not to an array!)将字符串添加到来自用户输入 Swift 的字符串(而不是数组!)
【发布时间】:2021-09-01 19:45:08
【问题描述】:

我有一个作业,我必须从 TextField 获取用户输入,检查它是否不为零,然后在 Label 中显示它。当用户输入新文本时,它应该显示在相同的标签中,在旧文本旁边(用空格分隔)。我不能使用数组。 我试图做 += 的事情,但它只显示最新的输入,没有以前的。

  @IBOutlet weak var textTextField: UITextField!

@IBOutlet weak var textLabel: UILabel!


@IBAction func type(_ sender: Any) {
    var text:String = ""
    var newText:String = ""
    if textTextField.text != nil {
        newText  = textTextField.text!
        text += newText
        textLabel.text =  "\(text)"
        textTextField.text = nil
    }
    

我在哪里犯错了? 最后它应该看起来像这样 screen interface example from my professor

【问题讨论】:

  • 您确定要textTextField.text = nil 吗?是要清除文字吗?
  • 只需将text 的声明移到函数之外,使其成为类属性。然后它将在函数调用之间保留新值
  • 将UITextField 的text 属性设置为nil 是不好的做法。根据文档,它永远不是nil——不像UILabel。默认值为空字符串
  • @vadian 是的。我也正要评论。值得一提的是,对于 UILabel text 属性,情况并非如此。

标签: swift string


【解决方案1】:

差不多了,您不需要text 或newText。

我还使用了if let ... 绑定,因此您无需在检查它是否为nil 后强制解包。

@IBOutlet weak var textTextField: UITextField!

@IBOutlet weak var textLabel: UILabel!


@IBAction func type(_ sender: Any) {
    if let current = textTextField.text {
        textLabel.text += current
        textTextField.text = nil
    }
}

【讨论】:

  • 谢谢!添加 += 真的让事情变得正常!
  • @KseniiaPiskun textLabel.text?.append(current) 应该也可以。确保使用一些文本或空字符串初始化您的标签。
  • @KseniiaPiskun 我还是觉得textTextField.text = nil 有点不寻常,你为什么要这么做?
  • bc 否则用户输入会停留在文本字段中(在 iphone/模拟器屏幕上),您需要在输入新输入之前将其删除。使用 textTextField.text = nil 我确保用户按下按钮后文本字段为空。也许有更好的方法,但我想出了这个)
  • @KseniiaPiskun 设置为空字符串 ("") 可能更好。正如其他人所说,建议您不要自己将其设置为nil。
猜你喜欢
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 2012-12-15
相关资源
最近更新 更多