【问题标题】:Avoiding Empty Entry避免空输入
【发布时间】:2015-03-29 11:05:14
【问题描述】:

伙计们如何避免将空项目添加到 toDoList 表?我一直忙于构建一个待办事项列表,当用户没有在文本字段中填写任何内容但他仍然可以将空项目添加到表中时遇到问题,并且当我尝试用空滑动表的行时输入我得到一个致命的错误!为什么会这样以及如何避免添加那些空数据?

好的,我将您的代码添加到我的 add Button 中:但这并没有太大帮助!

@IBAction func addItem(sender: AnyObject) {  
    if "" != item.text {
        // DO Something but don't fill the row (**item** is my text field)
        toDoList.append(item.text)
        item.text = ""

        NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList")

    }else{
         labelField.text = "Please enter an item!"
    }
}

【问题讨论】:

    标签: iphone xcode uitableview swift


    【解决方案1】:

    在添加项目的方法中,只需检查 UITextField 实例的 text 属性,如果它包含字符串,则添加项目

    if "" != textField.text {
    }
    

    虽然使用我给出的解决方案有一些缺点,例如用户可以输入空格作为其输入,但它可以完成工作。您也可以使用正则表达式来限制您希望用户输入的输入。

    【讨论】:

    • @"" 是 Objective-C,而不是 Swift :)
    • @MartinR 哦,是的,我的错,写得很快
    【解决方案2】:

    你可以像这样控制一个项目的输入

    if "" == textField.text {
    // DO Something but don't fill the row
    }
    

    而对于滑动问题,可以实现如下方法

    optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
        if commitEditingStyle == .Delete {
            // Delete the row, and the item in the array
        }
    }
    

    【讨论】:

      【解决方案3】:

      好的,解决了!我就是这样做的:

      if item.text != "" {
              // DO Something but don't fill the row
      
           toDoList.append(item.text)
      }else{
      
          labelField.text = "Please enter an item!"
          }
      

      【讨论】:

      • 我可能想在你得到其他错误之前进入,如果用户进入一个空间会发生什么?你想让他们想起一个空间吗?
      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多