在键盘外触摸时完成按钮操作 - Swift Xcode

时间:2015-08-31 02:33:50

标签: ios xcode swift

我使用以下代码在UITextfield'item'中输入值,然后点击按钮addButtontextfield中的值将附加到数组中,然后清除textfield。我还添加了一个代码,在外面触摸时会隐藏键盘。

问题是,在textfield中输入一个单词,然后触摸外面,按钮中的操作完成,甚至在按下按钮之前

@IBOutlet weak var item: UITextField!

@IBAction func addButton(sender: AnyObject) {

    toDoList.append(item.text!)
    item.text = ""
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.view.endEditing(true)

}

2 个答案:

答案 0 :(得分:1)

我不知道这个问题,但这对你很有帮助,因为你是swift的新手,

  1. 首先删除

     @IBOutlet weak var item: UITextField!  
    
    &   
    
     @IBAction func addButton(sender: AnyObject) {
    
      toDoList.append(item.text!)
      item.text = ""
     }
    
  2. 02.然后转到故事板,单击视图控制器,然后单击最后一个按钮,箭头指示向右。检查插座。删除项目并在该列表上添加按钮。

    1. 然后再次添加文本字段并向视图控制器添加按钮。 单击文本字段+ ctrl ad将视图控制器代码连接到该行,对addButton执行相同操作,使用内部触摸不触及外部

    2. 将这些函数添加到代码并运行项目。

      override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
      self.view.endEditing(true)
      

      }

      func textFieldShouldReturn(textField: UITextField) -> Bool {
      
      textField.resignFirstResponder()
      return true
      

      }

    3. 希望这些步骤对您有所帮助。如果没有发表评论

答案 1 :(得分:0)

将按钮拖入代码时,将事件设置为&#34;在内部触摸&#34;

相关问题