【问题标题】:Could I set vc's view becomeFirstResponder by touchesBegan func in storyboard?我可以在情节提要中通过 touchesBegan func 设置 vc 的视图 becomeFirstResponder 吗?
【发布时间】:2016-11-29 12:18:46
【问题描述】:

在代码中,我可以使用下面这个方法让vcviewbecomeFirstResponder,淡化keyboard的出现。

代码如下:

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

    self.view.endEditing(true)
}

我可以在我的故事板中设置这个function 吗?或者点击self.viewself.view.endEditing(true)有什么更简单的方法吗?

因为如果不这样做,我会将函数上部复制到几乎每个vc

【问题讨论】:

  • 在情节提要中添加getsure到你的VC,并添加一个手势功能,在手势内部添加结束编辑功能
  • @Anbu.Karthik 这样做的话,和override func touchesBegan方法差不多,因为代码量差不多。

标签: ios storyboard touchesbegan


【解决方案1】:

只需将它放在代码中的某个位置,它就会解决您的代码重复问题

extension UIViewController {
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
}

我不确定这样做是否是一种好方法,也许您想重新考虑退出文本字段响应者的架构问题,考虑您真正需要的内容。

【讨论】:

  • 如何在 Objective-c 中做到这一点?
  • 我的意思是扩展
【解决方案2】:

您可以创建 UIViewController 的扩展,然后为 touchesBegans 和您自己的 customTouchBegans 制作 swizzling 方法。查看 viewWillAppear 的 swizzling 方法示例 https://www.uraimo.com/2015/10/23/effective-method-swizzling-with-swift/

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多