Issue with Activity Indicator While loading data in UITableView

对着背影说爱祢 提交于 2020-01-06 05:39:06

问题


I'm getting record from server using php

As i'm getting 11 record currently so i want in starting i will show just 6 records and remaining next 5 record will show when user reached at last cell while scrolling. So this process is in working form, but the problem is while running, it working so fast that before reaching last row all records are already showing while scrolling and the activity indicator is just animating at the bottom of tableView.

I don't know what is the problem.

Also i want when user reached at last cell, activity indicator start animating while loading data .

Here is my code

import UIKit
import AlamofireImage

struct property{
let property_Id     : String
let propertyTitle   : String
let imageURL        : String
let user_Id         : String
let area            : String
let bed             : String
let unit            : String
let bath            : String
let price           : String
}
class searchRecordsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,favouriteButtonTableViewCellDelegate {

var y                           = 6
var m                           = 12
@IBOutlet weak var tableView    : UITableView!
var RESULT                      : [NSDictionary] = []
var myProperty                  = [property]()
var myPropertyCopy              = [property]()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

//MARK: Getting dictionary data from previous controller

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationItem.title = "Results"
    self.navigationController?.navigationBar.tintColor = UIColor.black

    //MARK: Getting dictionary data from previous controller
    for item in RESULT  {

        let propertyInfo = property(property_Id: String(item["propertyId"]! as! Int), propertyTitle: item["propertyTitle"]! as! String, imageURL: item["imagePath"]! as! String, user_Id: String(item["userId"]! as! Int), area: item["area"]! as! String, bed: item["bed"]! as! String, unit: item["unit"]! as! String, bath: item["bath"]! as! String, price: item["price"]! as! String )

        myProperty.append(propertyInfo)

    }
    //MARK: Inserting first 6 records in Array
    for i in 0 ..< 6 {
        if !(myProperty.indices.contains(i)) {
            break
        }
        myPropertyCopy.append(myProperty[i])

    }

}


func downloadImage(imagePath : String, theIMAGEVIEW : UIImageView) {
    let myUrl = URL(string: URL_IP+imagePath);

    //MARK: AlamofireImage to download the image
    theIMAGEVIEW.af_setImage(withURL: myUrl!, placeholderImage: #imageLiteral(resourceName: "addProperty"), filter: nil, progress: nil, runImageTransitionIfCached: true, completion: nil)
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "RecordCell") as! searchrecordsTableViewCell

    let property = myPropertyCopy[indexPath.row]
    cell.area.text = property.area+" "+property.unit
    if property.bath == ""{
        cell.bath.text = property.bath
    }
    else{
        cell.bath.text = property.bath+" Baths"
    }
    if property.bed == ""{
        cell.bed.text = property.bed
    }
    else{
        cell.bed.text = property.bed+" Baths"
    }
    cell.propertyTitle.text = property.propertyTitle
    cell.price.text = convertAMOUNT(price : property.price)
    downloadImage(imagePath: property.imageURL, theIMAGEVIEW: cell.myImageView)
    //----
    cell.delegate = self

    return cell
}


func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    if myPropertyCopy.count != myProperty.count{
        let lastRow = myPropertyCopy.count - 1
        if indexPath.row == lastRow {
            let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            spinner.startAnimating()
            spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))

            self.tableView.tableFooterView = spinner
            self.tableView.tableFooterView?.isHidden = false
            moreData()

        }

    }
}

func moreData(){

    for i in y ..< m {
        if !(myProperty.indices.contains(i)) {

            break

        }
        myPropertyCopy.append(myProperty[i])

    }
        y = y + 10
        m = m + 10
        self.tableView.reloadData()

}



}

currently my TableView looks like See output here

Thanks in Advance.


回答1:


After a long practice i have done my problem, i have just added UIScrollView delegate function for checking if the user reached at last cell then start activityIndicator for 3 seconds and then load data and that's it.

As i have just very small amount of data that's why i'm start ing UIactivityIndicator for 3 seconds before getting data.

 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    // UITableView only moves in one direction, y axis
    let currentOffset = scrollView.contentOffset.y
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height

    if maximumOffset - currentOffset <= 10.0 {
        let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)

        if myPropertyCopy.count != myProperty.count {

            //print("this is the last cell")

            spinner.startAnimating()
            spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
            spinner.hidesWhenStopped = true
            self.tableView.tableFooterView = spinner
            self.tableView.tableFooterView?.isHidden = false

            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                //MARK: Loading more data
                self.moreData()

            }

        }
        else{
            self.tableView.tableFooterView?.isHidden = true
            spinner.stopAnimating()
        }
    }

}


来源:https://stackoverflow.com/questions/50492284/issue-with-activity-indicator-while-loading-data-in-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!