怎么可以不使用按钮直接点击单元格它会显示地址?

时间:2015-09-26 09:11:56

标签: ios xcode swift

这是一个代码,它点击按钮获取我的位置后给我的地址,但我想不使用按钮的代码直接点击单元格它将显示地址 soucre代码:

let locationManager = CLLocationManager()
var location: CLLocation?
var updatingLocation = false
var lastLocationError: NSError?

let geocoder = CLGeocoder()
var placemark: CLPlacemark?
var performingReverseGeocoding = false
var lastGeocodingError: NSError?
var timer: NSTimer?

override func viewDidLoad()
{
    super.viewDidLoad()
    updateLabels()
    configureGetButton()
}
override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
}


@IBAction func getLocation()
{
    let authStatus = CLLocationManager.authorizationStatus()

    if authStatus == .NotDetermined
    {
        locationManager.requestWhenInUseAuthorization()
        return
    }

    if updatingLocation
    {
        stopLocationManager()

    } else
    {
        location = nil
        lastLocationError = nil
        placemark = nil
        lastGeocodingError = nil
        startLocationManager()
    }
    updateLabels()
    configureGetButton()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
    print("didFailWithError \(error)")
    if error.code == CLError.LocationUnknown.rawValue
    {
        return
    }

    lastLocationError = error
    stopLocationManager()
    updateLabels()
    configureGetButton()

}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let newLocation = locations.last
    print("didUpdateLocations \(newLocation)")
    if newLocation!.timestamp.timeIntervalSinceNow < -5
    {
        return
    }
    if newLocation!.horizontalAccuracy < 0
    {
        return
    }

    var distance = CLLocationDistance(DBL_MAX)
    if let location = location
    {
        distance = newLocation!.distanceFromLocation(location)
    }
    if location == nil || location!.horizontalAccuracy > newLocation!.horizontalAccuracy
    {
        lastLocationError = nil
        location = newLocation
        updateLabels()

        if newLocation!.horizontalAccuracy <= locationManager.desiredAccuracy
        {
            print("*** We're done!")
            stopLocationManager()
            configureGetButton()

            if distance > 0
            {
                performingReverseGeocoding = false
            }
        }

        if !performingReverseGeocoding
        {
            print("*** Going to geocode")
            performingReverseGeocoding = true
            geocoder.reverseGeocodeLocation(location!, completionHandler: {
                placemarks, error in

                print("*** Found placemarks: \(placemarks), error: \(error)")

                self.lastGeocodingError = error
                if error == nil && !placemarks!.isEmpty
                {
                    self.placemark = placemarks!.last
                }
                else
                {
                    self.placemark = nil
                }
                self.performingReverseGeocoding = false
               self.updateLabels()
            })
        }
    }
    else if distance < 1.0
    {
        let timeInterval = newLocation!.timestamp.timeIntervalSinceDate(location!.timestamp)
        if timeInterval > 10
        {
            print("**Force done!")
            stopLocationManager()
            updateLabels()
            configureGetButton()
        }
    }
}
var datePickerVisible = false

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("DatePickerCell")
if indexPath.section == 2 && indexPath.row == 1
{

if cell == nil {
    cell = UITableViewCell(style: .Default,
        reuseIdentifier: "DatePickerCell")
    cell.selectionStyle = .None
    // 3
    let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 320, height: 216))
    datePicker.tag = 100
    cell.contentView.addSubview(datePicker)
    // 4
    datePicker.addTarget(self, action: Selector("getLocation"), forControlEvents: .ValueChanged)
}

return cell
}else
{
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)

}

}

func showLocationServiceDeniedAlert()
{
    let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable location services for this app in settings.", preferredStyle: .Alert)
    let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alert.addAction(okAction)
    presentViewController(alert, animated: true, completion: nil)


}


func startLocationManager()
{
    if CLLocationManager.locationServicesEnabled()
    {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
        updatingLocation = true
    }
}
func stopLocationManager()
{
    if updatingLocation
    {
       if let timer = timer
       {
        timer.invalidate()
        }
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil
        updatingLocation = false

    }
}
func configureGetButton()
{
    if updatingLocation
    {
        getButton.setTitle("Stop", forState: .Normal)
    }
    else
    {
        getButton.setTitle("GetMyLocation", forState: .Normal)
    }

}
func stringFromPlacemark(placemark: CLPlacemark) -> String
{
    return   "\(placemark.subThoroughfare) \(placemark.thoroughfare)\n" +
    "\(placemark.locality) \(placemark.administrativeArea)" +
    "\(placemark.postalCode)"
}
func didTimeOut()
{
    print("*** Time Out")
    if location == nil
    {
        stopLocationManager()
        lastLocationError = NSError(domain: "MyLocationsErrorDomain", code: 1, userInfo: nil)
        updateLabels()
        configureGetButton()
    }
}


func updateLabels()
{
    if let location = location
    {

        if let placemark = placemark
        {
            addressLabel.text = stringFromPlacemark(placemark)

        }else if performingReverseGeocoding
        {
            addressLabel.text = "Eror Finding Address"
        }
        else
        {
            addressLabel.text = "No Address Found"
        }
    }
    else
    {
        addressLabel.text = ""
        var statusMessage: String
        if let error = lastLocationError
        {
            if error.domain == kCLErrorDomain && error.code == CLError.Denied.rawValue
            {
                statusMessage = "Location Services Disabled"
            }
            else
            {
                statusMessage = "Error Getting Location"
            }

        }
        else if !CLLocationManager.locationServicesEnabled()
        {
            statusMessage = "Location Services Disabled"
        }
        else if updatingLocation
        {
            statusMessage = "Searching.."
        }
        else
        {
            statusMessage = "Tap 'Get My Location' to start"
        }
    }

  }
}

2 个答案:

答案 0 :(得分:2)

只需添加此方法

func tableView(_ tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath)
{
      if(indexPath.section == 0)
      {
           let authStatus = CLLocationManager.authorizationStatus()

           if authStatus == .NotDetermined
           {
               locationManager.requestWhenInUseAuthorization()
              return
           }

           if updatingLocation
           {
               stopLocationManager()

           } else
           {
               location = nil
               lastLocationError = nil
               placemark = nil
               lastGeocodingError = nil
               startLocationManager()
           }
           updateLabels()
           configureGetButton()
      }
      else
      {
           //that is second section
      }
}

答案 1 :(得分:1)

您有三种选择:

  1. 您可以在延迟后使用以下代码调用按钮操作:

    let seconds = 1.0
    let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per seconds
    let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(dispatchTime, dispatch_get_main_queue(), {
        // here code perfomed with delay
    })
    
  2. 您可以添加tapGestureRecognizer之类的内容:

    let backgoroundTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
    tableView.addGestureRecognizer(backgoroundTap)
    

    并将该函数调用为:

    func DismissKeyboard(){
        view.endEditing(true)
    }
    
  3. 或者您可以按下按钮按

    self.button.sendActionsForControlEvents(UIControlEvents.TouchUpInside)