加载UITableView后停止活动指示器

时间:2016-01-14 06:09:52

标签: ios swift uitableview

如何在按下刷新按钮后自动停止活动指示,并在UITableview JSON中完成内容加载

我已经有代码开始旋转和按钮

这是完整的代码

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var json_data_url = "http://www.howtotechworld.com/json_table_view_images%20(1).json"
    var image_base_url = ""
    var isProgressShowing = true;

    var TableData:Array< datastruct > = Array < datastruct >()

    enum ErrorHandler:ErrorType
    {
        case ErrorFetchingResults
    }


    struct datastruct
    {
        var imageurl:String?
        var description:String?
        var image:UIImage? = nil

        init(add: NSDictionary)
        {
            imageurl = add["url"] as? String
            description = add["description"] as? String
        }
    }

    @IBOutlet var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableview.dataSource = self
        tableview.delegate = self

        get_data_from_url(json_data_url)
    }

    override func viewWillAppear(animated: Bool) {
        let barButtonItem = UIBarButtonItem(title: "Refresh", style: .Plain, target: self, action: "refreshTapped");
        self.navigationItem.rightBarButtonItem = barButtonItem;
    }

    func refreshTapped() {
        addProgressIndicator(isProgressShowing);
        get_data_from_url(json_data_url)
    }

    func addProgressIndicator(show : Bool) {
        isProgressShowing = !show;
        if(show) {
            let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
            myActivityIndicator.startAnimating()
            let barButtonItem = UIBarButtonItem(customView: myActivityIndicator)
            self.navigationItem.rightBarButtonItem = barButtonItem
        } else {
            self.navigationItem.rightBarButtonItem = nil;
        }




    }




    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

        let data = TableData[indexPath.row]


        cell.textLabel?.text = data.description

        if (data.image == nil)
        {
            cell.imageView?.image = UIImage(named:"image.jpg")
            load_image(image_base_url + data.imageurl!, imageview: cell.imageView!, index: indexPath.row)
        }
        else
        {
            cell.imageView?.image = TableData[indexPath.row].image
        }

        return cell

    }

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







    func get_data_from_url(url:String)
    {


        let url:NSURL = NSURL(string: url)!
        let session = NSURLSession.sharedSession()

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData


        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
                print("error")
                return
            }

            dispatch_async(dispatch_get_main_queue(), {
                self.extract_json(data!)
                return
            })

        }

        task.resume()

    }


    func extract_json(jsonData:NSData)
    {
        let json: AnyObject?
        do {
            json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
        } catch {
            json = nil
            return
        }

        if let list = json as? NSArray
        {
            for (var i = 0; i < list.count ; i++ )
            {
                if let data_block = list[i] as? NSDictionary
                {

                    TableData.append(datastruct(add: data_block))
                }
            }

            do
            {
                try read()
            }
            catch
            {
            }

            do_table_refresh()

        }


    }




    func do_table_refresh()
    {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableview.reloadData()
            return
        })
    }


    func load_image(urlString:String, imageview:UIImageView, index:NSInteger)
    {

        let url:NSURL = NSURL(string: urlString)!
        let session = NSURLSession.sharedSession()

        let task = session.downloadTaskWithURL(url) {
            (
            let location, let response, let error) in

            guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
                print("error")
                return
            }

            let imageData = NSData(contentsOfURL: location!) 

            dispatch_async(dispatch_get_main_queue(), { 


                self.TableData[index].image = UIImage(data: imageData!) 
                self.save(index,image: self.TableData[index].image!) 

                imageview.image = self.TableData[index].image 
                return 
            }) 


        } 

        task.resume() 


    } 




    func read() throws 
    { 

        do 
        { 
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
            let managedContext = appDelegate.managedObjectContext! 
            let fetchRequest = NSFetchRequest(entityName: "Images") 

            let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) 

            for (var i=0; i < fetchedResults.count; i++) 
            { 
                let single_result = fetchedResults[i] 
                let index = single_result.valueForKey("index") as! NSInteger 
                let img: NSData? = single_result.valueForKey("image") as? NSData 

                TableData[index].image = UIImage(data: img!) 

            } 

        } 
        catch 
        { 
            print("error") 
            throw ErrorHandler.ErrorFetchingResults 
        } 

    } 

    func save(id:Int,image:UIImage) 
    { 
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
        let managedContext = appDelegate.managedObjectContext! 

        let entity = NSEntityDescription.entityForName("Images", 
            inManagedObjectContext: managedContext) 
        let options = NSManagedObject(entity: entity!, 
            insertIntoManagedObjectContext:managedContext) 

        let newImageData = UIImageJPEGRepresentation(image,1) 

        options.setValue(id, forKey: "index") 
        options.setValue(newImageData, forKey: "image") 

        do { 
            try managedContext.save() 
        } catch 
        { 
            print("error") 
        } 

    } 


}

3 个答案:

答案 0 :(得分:3)

您需要保留对myActivityIndicator的引用,并在do_table_refresh()中将其停止,如下所示。

func do_table_refresh()
{
    dispatch_async(dispatch_get_main_queue(), {
        self.tableview.reloadData()

         myActivityIndicator.stopAnimating()
         return
        })
    }

编辑:在查看问题中的代码之后,我想了一下。

如果您想使用myActivitIndicator隐藏addProgressIndicator(isProgressShowing),则必须确保isProgressShowing设置为FALSE,然后在我上面给出的代码中,替换{ {1}} myActivityIndicator.stopAnimating()

您还需要更新addProgressIndicator(isProgressShowing)功能并将addProgressIndicator添加到其他条件。

答案 1 :(得分:1)

如果我理解你的问题,那么我认为以下是你想要的。

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
    //end of loading
    //for example [activityIndicator stopAnimating];
}
}

对于swift来说就像这样

func cellForRowAtIndexPath(_ indexPath: NSIndexPath) -> UITableViewCell?{
if(indexPath.row = tableView.indexPathsForVisibleRows().lastObject().row{
    //end of loading
    //for example [activityIndicator stopAnimating];
}
return yourCell;

}

我不太了解,但我想你会知道怎么做。

答案 2 :(得分:1)

do_table_refresh()addProgressIndicator(!isProgressShowing);

之后添加此代码