【问题标题】:Swift Pull to Refresh doesn't ShowSwift Pull to Refresh 不显示
【发布时间】:2015-08-07 23:50:51
【问题描述】:

我已成功在我的 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

    }
}


}

非常感谢。

【问题讨论】:

  • 您使用了刷新视图但没有正确使用它们的属性。
  • 嗨,Ghanshyam,你能建议我做些改变吗?我是 Swift 的新手。谢谢

标签: ios swift locationmanager pull-to-refresh


【解决方案1】:

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

  1. 尝试使用tableView.addSubview(refreshControl),而不是self.tableView.insertSubview(refreshControl, atIndex: 0)。看看add和insert subview的区别here

  2. 定义另一个函数来填充视图。例如。 func populateView()

  3. self.handleRefresh() 替换为self.populateView()

  4. 替换

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

    self.refreshControl.addTarget(
        self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged
    )
    
  5. func handleRefresh() 中使用refreshControl.beginRefreshing() 发起刷新,然后移除所有对象,重新加载tableView,结束刷新并填充视图。

编辑

我误解了你的问题。

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

    这是因为 UITableViewControllerrefreshControl 是预先安装好的,而普通的 ViewController 没有。

  2. 那该怎么办?

    这是一个定义一个惰性实例化变量的 sn-p,它创建和配置一个 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)

希望这能帮助你理解!

【讨论】:

  • Ok Boopathy,今晚我尝试替换您建议的更改,但为什么我的代码在其他视图上运行良好?
  • Mit,我已经编辑了答案。检查它,如果它对你有帮助,请告诉我。编码愉快!
  • 嗨 Boopathy,我已经尝试过你的解决方案,但结果是一样的。使用我的代码,我已经成功创建了一个带有 refreshControl 的 tableView。我的代码工作的视图等于不工作的视图。所有都包含 tableView 视图并且是简单的 UIViewController ,而不是 UITableViewController。由于情节提要中的某些参数在视图之间有所不同,这可能是一个问题?
猜你喜欢
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 2014-05-11
  • 1970-01-01
相关资源
最近更新 更多