Swift Detect Touch Anywhere

时间:2015-01-06 00:58:33

标签: swift touch global modalviewcontroller popover

我正在编写我的第一个应用程序,使用Swift,我需要一个弹出窗口或模态视图,可以通过触摸屏幕上的任何位置来解除。

我正在编写一个IOU应用程序,目前正在处理用户进入贷方的视图以及他们借出多少钱。显然,每个贷方都需要有一个唯一的名称,每当用户试图输入相同的名称两次要求他们更改名称时,我就会想要一个弹出框或模态视图。为了减轻刺激因素,我想做到这一点,以便用户可以点击屏幕上的任何地方来消除警告,而不是特定的按钮。

我找到了这个答案:Detect touch globally,我认为它可能对我有用,但我对Objective-C一无所知,只是Swift,并且无法理解该怎么做。

7 个答案:

答案 0 :(得分:7)

解雇模态视图变得异常简单。您只需拨打dismissViewControllerAnimated(true, completion: nil)即可。因此,要做我想做的事,我需要做的就是:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent)
{
  dismissViewControllerAnimated(true, completion: nil)
  super.touchesEnded(touches, withEvent: event)
}

答案 1 :(得分:4)

Swift 3.0

// Add this to your UIViewController class

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

           //Do thing here
        }

答案 2 :(得分:2)

我个人不知道如何解雇popover,因为我没有使用它们,但我可以解决你的一个问题。您说当用户触摸屏幕上的任何位置时,您想要关闭弹出框或模态。这是一个在任何位置触摸屏幕时触发的功能,您可以在apple documents中阅读更多相关信息。

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    }

答案 3 :(得分:1)

通过添加UIGestureRecognizer,我发现了一种很好的方法。

在AppDelegate中,通过将其添加到您的

中,使其符合UIGestureRecognizerDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, UIGestureRecognizerDelegate {

...

添加tapGestures

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // add tapGestures to entire application
        let tapGesture = UITapGestureRecognizer(target: self, action: nil)
        tapGesture.delegate = self
        window?.addGestureRecognizer(tapGesture)

        return true
    }

添加gestureRecognizer协议功能:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    // User tapped on screen, do something

    return false
}

答案 4 :(得分:1)

Swift 4.2:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // Touch began
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        // Touch end
    }

答案 5 :(得分:0)

  

我想这样做,以便用户可以点按屏幕上的任意位置来取消警告,而不是点击特定按钮。

这可能是一个非常非常糟糕的想法,你可能会遇到与你的文本字段或模态视图中的其他元素的手势碰撞,或者你可能会在用户意外解雇模态时让用户感到不安,但是嘿,无论你有什么蠢货船。

在模态视图中获取最顶层视图控制器的视图。如果它是包含UINavigationController的{​​{1}},您可以在模式YourModalViewController {<1}}中执行此操作:

viewDidLoad

然后从手势识别器的动作方法中解除你的模态。

答案 6 :(得分:-1)

我正在处理一个应用程序。我们需要保持 10-15 分钟的会话。为此,我正在寻找用户的触摸事件。

我已经在应用程序中安装了基本控制器。所以我更新了 viewwillappear 上的会话。我不需要任何触摸事件。