【问题标题】:Dismissing Keyboard on Custom UITextField关闭自定义 UITextField 上的键盘
【发布时间】:2016-06-30 07:01:55
【问题描述】:

我将TextFieldEffects 用于自定义 UITextFields。创建文本字段非常简单。

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
        let textField = HoshiTextField(frame: textFieldFrame)
        textField.placeholderColor = .darkGrayColor()
        textField.foregroundColor = .lightGrayColor()

        view.addSubView(textField) 
   }
}

为了解除键盘,我尝试做我通常做的事情,但不幸的是没有运气。

func textFieldShouldReturn(textField: HoshiTextField) -> Bool {
    self.view.endEditing(true)
    return false
}

func dismissKeyboard() {
    view.endEditing(true)
}

你有什么建议吗?

【问题讨论】:

    标签: ios swift keyboard uitextfield uikeyboard


    【解决方案1】:

    确认你的 ViewController 的 UITextFieldDelegate 协议并分配textField.delegate = self,然后实现以下委托方法:

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
      }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
      }
    

    为了更好的理解,请看我的代码snipet

    【讨论】:

    • 通过添加 delegate = self,textFieldShouldReturn() 开始工作。但是,dismissKeyboard()(点击外部)仍然不起作用。
    • 实现触摸开始方法覆盖 func touchesBegan(touches: Set, withEvent event: UIEvent?) { self.view.endEditing(true) }
    • 您能否将其包含在您的答案中,以便我接受它作为正确答案?
    • 我使用了(这个答案)[stackoverflow.com/a/32281860/4705339],因为你的那个给了我一个错误。不过还是谢谢
    【解决方案2】:
    class ViewController: UIViewController, UITextFieldDelegate //add this protocol 
    {
    ...
      func ... {
        let textField = HoshiTextField(frame: textFieldFrame)
        textField.placeholderColor = .darkGrayColor()
        textField.foregroundColor = .lightGrayColor()
        textField.delegate = self
      }
    }
    

    【讨论】:

    • 我也试过了,但我收到错误“无法将'YourViewController'类型的值分配给'UITextFieldDelegate?'”可能是什么解决方法?
    • textField.delegate = self 这是发生错误的地方。我认为答案是在顶部定义它(例如,如果我在 Storyboard 上创建 UITextField,我会 ctrl+drag,但是当我以编程方式创建它时,也许我也需要在顶部定义它)。你怎么看?
    • @senty 你不需要这样做。你可以像你正在做的那样创造。请张贴代码。也许全班ViewController
    • 更新: 返回按钮 (textFieldShouldReturn) 现在可以使用,但另一个按钮不行(dismissKeyboard,当我点击外面时)
    • @senty 要点击外部,您必须搜索更多。你必须做更多的事情。这是另一个问题。请标记正确答案并提出另一个问题。感谢您。你可以在这里参考dismisskeyboard:stackoverflow.com/questions/32281651/…
    【解决方案3】:

    为您的 textField 设置委托,也许它会起作用!

    【讨论】:

    • 我该怎么做?它嵌入在 UIViewController 中。我尝试使用 textField.delegate = self 但它不允许我这样做,因为 self 是 UIViewController。正确的做法是什么?谢谢
    • 设置类似:class YourViewController: UIViewController, UITextFieldDelegate 参考:sourcefreeze.com/uitextfield-and-uitextfield-delegate-in-swift
    猜你喜欢
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多