【问题标题】:Swift- Find location after shake motion endsSwift-摇动结束后查找位置
【发布时间】:2017-03-26 20:28:36
【问题描述】:

我知道如何做摇动手势和如何分别找到位置,但是我不知道用户摇动设备后如何找到位置。我有 xcode 6.4 版。

现在我有一个动作结束功能。还有一个 showUserLocation 函数。
我想在 motionEnded 中添加一个调用 showUserLocation 的语句,以便在用户摇动手机时找到该位置。

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {

      ?????  

    }

// Showing the user location
func showUserLocation(sender : AnyObject) {
    let status = CLLocationManager.authorizationStatus()

    //Asking for authorization to display current location
    if status == CLAuthorizationStatus.NotDetermined {
        locationManager.requestWhenInUseAuthorization()
    } else {
        locationManager.startUpdatingLocation()
    }

【问题讨论】:

  • 这个问题太宽泛了,答案很简单,虽然可能很难实现,因为在软件开发中几乎总是如此,在手机震动之后,在你的代码中,你知道震动已经发生了,现在找到位置
  • 更具体地说:这些括号中的内容会覆盖 func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { ????连接到我设置的 showUserLocation 函数
  • 你不能问这样的问题,在 cmets 中发布代码太难,任何人都无法理解并给你答案,括号中是你想要的任何代码,以某种形式或语法,你可以如果在范围内,在正确的线程上可访问,则调用您的函数
  • Brian,感谢您抽出宝贵时间帮助我解决此问题。我正在寻找更具体的答案。我现在将编辑我的问题,希望能更清楚。

标签: ios swift shake locate


【解决方案1】:

您的问题与摇晃动作结束或呼叫位置无关。您的问题是 Swift 的基本语法和对任何编程语言的一般理解之一。

您用于获取位置的代码实现被“装箱”到一个动作函数中,可能是一个 UIButton touchup,其中需要发送者作为参数。但是您根本不使用 sender 来获取位置信息,因此很容易将此实现移动到它自己的函数 showUserLocationHelper 中,因此动作函数可以调用 getLocation 并且摇动运动可以调用 get location。

你的动作函数的名称:showUserLocation 的名字不好,它应该有一个像 btnShowUserLocationTouchUpInside 这样的名字,一个长的名字,但不会像你命名你的动作函数那样混淆,而不是尝试在 motionEnded 中使用。

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
    //you can't pass the sender so couldn't call your showUserLocation action function,
    //so move implementation of showUserLocation to showUserLocationHelper and now you can do what you need after shake event
    showUserLocationHelper()
}

// Showing the user location
//this is an action function for some UI element like a UIButton and the sender is required to be passed for this function to fire thus, motionEnded cannot directly call it
//but you do not use sender at all
func showUserLocation(sender : AnyObject) {
    showUserLocationHelper()
}

func showUserLocationHelper() {
    let status = CLLocationManager.authorizationStatus()

    //Asking for authorization to display current location
    if status == CLAuthorizationStatus.NotDetermined {
        locationManager.requestWhenInUseAuthorization()
    } else {
        locationManager.startUpdatingLocation()
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多