这是一个代码,它是在单击按钮获得我的位置后给我地址,但是我想要代码不使用按钮直接单击单元格,它将显示address 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"
        }
    }
  }
}发布于 2015-09-26 09:34:45
只需添加此方法
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
      }
}发布于 2015-09-26 09:27:41
你有三个选择:
tapGestureRecognizer,例如:
设backgoroundTap: UITapGestureRecognizer =UITapGestureRecognizer(目标: self,action:"DismissKeyboard")
并调用该函数如下:
func DismissKeyboard(){ view.endEditing(true) }https://stackoverflow.com/questions/32795498
复制相似问题