首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >怎么可能不使用按钮直接单击单元格,它将显示地址?

怎么可能不使用按钮直接单击单元格,它将显示地址?
EN

Stack Overflow用户
提问于 2015-09-26 09:11:56
回答 2查看 67关注 0票数 0

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

代码语言:javascript
复制
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"
        }
    }

  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-26 09:34:45

只需添加此方法

代码语言:javascript
复制
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
      }
}
票数 2
EN

Stack Overflow用户

发布于 2015-09-26 09:27:41

你有三个选择:

  1. 可以使用以下代码在延迟后调用按钮操作: 让秒= 1.0让延迟=秒*双(NSEC_PER_SEC) //纳秒每秒让dispatchTime = dispatch_time(DISPATCH_TIME_NOW,Int64(延迟)) dispatch_after(dispatchTime,dispatch_get_main_queue(),{ //这里的代码用延迟}完成)
  2. 您可以添加tapGestureRecognizer,例如: 设backgoroundTap: UITapGestureRecognizer =UITapGestureRecognizer(目标: self,action:"DismissKeyboard") 并调用该函数如下: func DismissKeyboard(){ view.endEditing(true) }
  3. 或者你可以假装按下按钮 self.button.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32795498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档