Swift Pull to Refresh不显示

时间:2015-05-26 10:44:30

标签: ios swift locationmanager pull-to-refresh

我在我的Swift项目上成功地在UITableView上添加了Pull To Refresh,在另一个ViewController上我无法显示它。 在其他视图中,没有LocationManager函数,代码是相同的。 我不知道我的错误在哪里!

在我的代码下面:

import UIKit
import CoreLocation



class MainViewController: UIViewController, UITableViewDataSource,   UITableViewDelegate, CLLocationManagerDelegate {

var locationManager: CLLocationManager!
var locationCoordinates: CLLocationCoordinate2D!

@IBOutlet weak var bannerView: GADBannerView!

var dati = NSMutableArray()
var datiComplete = NSDictionary()
@IBOutlet weak var tableView: UITableView!

var arrayOfData: [MyData] = [MyData]()

var url:NSURL!
var refreshControl = UIRefreshControl()
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {

    super.viewDidLoad()


    self.locationManager = CLLocationManager()
    self.locationManager.delegate           = self
    self.locationManager.desiredAccuracy    = kCLLocationAccuracyBest   //Battery drain!
    self.locationManager.distanceFilter     = 1
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()

    searchUser()


    self.dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    self.dateFormatter.timeStyle = NSDateFormatterStyle.LongStyle


    self.refreshControl = UIRefreshControl()
    self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)


    self.tableView.insertSubview(refreshControl, atIndex: 0)

    self.handleRefresh()
}
func refresh(sender:AnyObject)
{
    println("Refresh work!")
    self.handleRefresh()
}
func handleRefresh() {

    if locationManager.location != nil {

        url = NSURL(string: "http://www.myURL.com/data.php?lat=\(locationManager.location.coordinate.latitude)&lon=\(locationManager.location.coordinate.longitude)&max=15&when=now")!
    } else {


        url = NSURL(string: "http://www.myURL.com/data.php?lat=41&lon=11&max=10&when=now")!
    }



    //println("Call URL!!")
    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request.HTTPMethod = "GET"

    request.setValue("application/json", forHTTPHeaderField: "Accept")
    var reponseError: NSError?
    var response: NSURLResponse?

    //var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
        response, data, error in

        if (error != nil) {
            return
        }

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            var error: NSError?
            self.dati = (NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as! NSDictionary)["spots"] as! NSMutableArray

            if (error != nil){
                return
            }

            // **** Json Parsing *****

            dispatch_async(dispatch_get_main_queue()){
                self.tableView.reloadData()
                self.tableView.delegate = self

                self.tableView.dataSource = self


            }

        }

    })
    let now = NSDate()
    let updateString = "Last Updated at " + self.dateFormatter.stringFromDate(now)
    self.refreshControl.attributedTitle = NSAttributedString(string: updateString)
    if self.refreshControl.refreshing
    {
        self.refreshControl.endRefreshing()
    }

    self.tableView?.reloadData()
    refreshControl.endRefreshing()
}

func searchUser(){
    println("Start Search User")
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
    println("Start Location Manager Func")
    self.locationCoordinates = manager.location.coordinate
    self.locationManager.stopUpdatingLocation()
    println("**************** locations = \(self.locationCoordinates.latitude) \(self.locationCoordinates.longitude)")
}



override func viewWillAppear(animated: Bool) {

    super.viewWillAppear(animated)

    self.setNavigationBarItem()

}



override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arrayOfData.count    
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: ViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ViewCell
    cell.backgroundColor = UIColor.whiteColor()
    let usr = arrayOfData[indexPath.row]    
    cell.setCell(<Cell-data>)

    return cell

}

var selectedSpot:String? = nil
var selectedSpotIndex:Int? = nil

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "GoSpotDetails" {

        var tabBarC : TabBarController = segue.destinationViewController as! TabBarController


        var caseIndex = tableView!.indexPathForSelectedRow()!.row
        var selectedCase = self.arrayOfSpotsTemp[caseIndex]

        tabBarC.DataDetail = selectedCase

    }
}


}

非常感谢。

1 个答案:

答案 0 :(得分:0)

嗯,您的代码需要进行大量更改。我来给你一些建议。

  1. 而不是self.tableView.insertSubview(refreshControl, atIndex: 0)尝试使用tableView.addSubview(refreshControl)。查看添加和插入子视图here
  2. 之间的差异
  3. 定义另一个填充视图的函数。例如。 func populateView()
  4. self.handleRefresh()替换为self.populateView()
  5. 替换

    self.refreshControl.addTarget(
        self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged
    ) 
    

    self.refreshControl.addTarget(
        self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged
    )
    
  6. func handleRefresh()中使用refreshControl.beginRefreshing()启动刷新,然后删除所有对象,重新加载tableView,结束刷新并填充视图。
  7. 修改

    我误解了你的问题。

    1. 为什么它不在其他视图中工作?

      因为在UITableViewController refreshControl中预先拟合,常规ViewController不会。

    2. 那该怎么办?

      这是一个片段,定义了一个懒惰的实例化变量,用于创建和配置UIRefreshControl:

      lazy var refreshControl: UIRefreshControl = {
          let refreshControl = UIRefreshControl()
          refreshControl.addTarget(
              self, action: "handleRefresh", forControlEvents: .ValueChanged
          )
          return refreshControl
      }()
      
    3. viewDidLoad()中添加UIRefreshControl作为tableView的子视图:   self.tableView.addSubview(self.refreshControl)

    4. 希望这有助于您理解!