UIRefreshController Топ-2 строки в табличном представлении неактивны
Просто начну, скажу, что я новичок в этом, но в любом случае.
У меня настроено приложение, где, если вы нажмете на строку tableview
это приведет вас к карте выбранного вами места. Когда я закомментирую свой код для моего UIRefreshControl
все работает так, как я хочу, но когда я но возвращаю его, я не могу нажать на верхние два ряда tableview
,
Пожалуйста, найдите ниже код, который я комментирую.
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to See Closest Locations")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
Весь код
import UIKit
import Parse
var manager: CLLocationManager!
var latitude1: CLLocationDegrees = 0
var longitude1: CLLocationDegrees = 0
var distances = [CLLocationDistance]()
var places = [Dictionary<String,String>()]
var activeplace = -1
var refresher: UIRefreshControl!
class TableViewController: UITableViewController, CLLocationManagerDelegate {
func refresh () {
var newPlaces = [Dictionary<String,String>()]
var newDistances = [CLLocationDistance]()
if newPlaces.count == 1 {
newPlaces.removeAtIndex(0)}
let query = PFQuery(className: "Lights")
query.selectKeys(["name","Geo"])
query.whereKey("Geo", nearGeoPoint:PFGeoPoint(latitude: latitude1, longitude: longitude1))
query.limit = 200
query.findObjectsInBackgroundWithBlock({ (nameU, error) -> Void in
if error != nil {
print(error)
} else {
if let objects = nameU {
for object in objects {
let name = object["name"] as! String
let geo = object["Geo"] as! PFGeoPoint
let lat = geo.latitude
let lon = geo.longitude
let lightLocation = CLLocationCoordinate2DMake(lat, lon)
let LightCLLocation = CLLocation(latitude: lightLocation.latitude, longitude: lightLocation.longitude)
let userLocation1 = CLLocation(latitude: latitude1, longitude: longitude1)
let distance = userLocation1.distanceFromLocation(LightCLLocation)
let distance1 = round(distance/100 * 0.621371)
newDistances.append(distance1/10)
newPlaces.append(["name":name,"lat":"\(lat)","lon":"\(lon)"])
}
}
places.removeAll()
distances.removeAll()
places = newPlaces
distances = newDistances
}
self.tableView.reloadData()
refresher.endRefreshing()
})
}
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to See Closest Locations")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOSApplicationExtension 8.0, *) {
manager.requestWhenInUseAuthorization()
} else {
// Fallback on earlier versions
}
manager.startUpdatingLocation()
if places.count == 1 {
places.removeAtIndex(0)
}
let query = PFQuery(className: "Lights")
query.selectKeys(["name","Geo"])
query.whereKey("Geo", nearGeoPoint:PFGeoPoint(latitude: latitude1, longitude: longitude1))
query.limit = 200
query.findObjectsInBackgroundWithBlock({ (nameU, error) -> Void in
if error != nil {
print(error)
} else {
// needs [PFObject] added
if let objects = nameU {
for object in objects {
let name = object["name"] as! String
let geo = object["Geo"] as! PFGeoPoint
let lat = geo.latitude
let lon = geo.longitude
let lightLocation = CLLocationCoordinate2DMake(lat, lon)
let LightCLLocation = CLLocation(latitude: lightLocation.latitude, longitude: lightLocation.longitude)
let userLocation1 = CLLocation(latitude: latitude1, longitude: longitude1)
let distance = userLocation1.distanceFromLocation(LightCLLocation)
let distance1 = round(distance/100 * 0.621371)
distances.append(distance1/10)
places.append(["name":name,"lat":"\(lat)","lon":"\(lon)"])
self.tableView.reloadData()
}
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return places.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = places[indexPath.row]["name"]! + " - " + String(distances[indexPath.row]) + " Miles Away"
return cell
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
activeplace = indexPath.row
return indexPath
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "newPlace" {
activeplace = -1
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
latitude1 = userLocation.coordinate.latitude
longitude1 = userLocation.coordinate.longitude
}
Спасибо
2 ответа
Я тоже боролся с этой проблемой, но, к счастью, все оказалось очень просто. Отправьте UIRefreshControl обратно в ViewDidLoad, и все готово!
Swift:
tableView.sendSubviewToBack (обновить)
Objective-C:
[tableView sendSubviewToBack: refresh];
Убедитесь, что ваше целевое действие правильно. Когда закончите обновление, вызовите этот метод, чтобы остановить и скрыть UIRefreshControl.
refresh.endRefreshing()