UITableFacebook 응용 프로그램처럼 아래로 스크롤할 때 더 많이 로드됩니다.
저는 SQLite를 사용하는 애플리케이션을 개발하고 있습니다.페이징 메커니즘을 사용하여 사용자 목록(UITableView)을 표시합니다.사용자가 목록 끝으로 스크롤할 때 내 목록에 더 많은 데이터를 로드하는 방법을 알려줄 수 있는 사람이 있습니까(Facebook 애플리케이션의 홈 페이지에서처럼)?
현재 위치에 대한 확인을 추가하여 이 작업을 수행할 수 있습니다.cellForRowAtIndexPath:
이 .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Classic start method
static NSString *cellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
}
MyData *data = [self.dataArray objectAtIndex:indexPath.row];
// Do your cell customisation
// cell.titleLabel.text = data.title;
BOOL lastItemReached = [data isEqual:[[self.dataArray] lastObject]];
if (!lastItemReached && indexPath.row == [self.dataArray count] - 1)
{
[self launchReload];
}
}
EDIT : 재귀 호출을 방지하기 위해 마지막 항목에 대한 검사를 추가했습니다.마지막 항목에 도달했는지 여부를 정의하는 방법을 구현해야 합니다.
EDIT2 : 마지막으로 도달한 항목 설명
스위프트
방법 1: 맨 아래로 스크롤했습니까?
이것은 페드로 로망의 답변의 스위프트 버전입니다.사용자가 스크롤을 멈추면 하단에 도달했는지 확인합니다.
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
// Change 10.0 to adjust the distance from bottom
if maximumOffset - currentOffset <= 10.0 {
self.loadMore()
}
}
방법 2: 마지막 행에 도달했습니다.
그리고 여기 sinyuX의 Swift 버전의 답변이 있습니다.사용자가 마지막 행에 도달했는지 확인합니다.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// set up cell
// ...
// Check if the last row number is the same as the last current data element
if indexPath.row == self.dataArray.count - 1 {
self.loadMore()
}
}
예loadMore()
방법
데이터 배치를 가져오기 위해 이 세 가지 클래스 변수를 설정했습니다.
// number of items to be fetched each time (i.e., database LIMIT)
let itemsPerBatch = 50
// Where to start fetching items (database OFFSET)
var offset = 0
// a flag for when all database items have already been loaded
var reachedEndOfItems = false
데이터베이스에서 테이블 보기로 더 많은 항목을 로드하는 기능입니다.
func loadMore() {
// don't bother doing another db query if already have everything
guard !self.reachedEndOfItems else {
return
}
// query the db on a background thread
DispatchQueue.global(qos: .background).async {
// determine the range of data items to fetch
var thisBatchOfItems: [MyObjects]?
let start = self.offset
let end = self.offset + self.itemsPerBatch
// query the database
do {
// SQLite.swift wrapper
thisBatchOfItems = try MyDataHelper.findRange(start..<end)
} catch _ {
print("query failed")
}
// update UITableView with new batch of items on main thread after query finishes
DispatchQueue.main.async {
if let newItems = thisBatchOfItems {
// append the new items to the data source for the table view
self.myObjectArray.appendContentsOf(newItems)
// reload the table view
self.tableView.reloadData()
// check if this was the last of the data
if newItems.count < self.itemsPerBatch {
self.reachedEndOfItems = true
print("reached end of data. Batch count: \(newItems.count)")
}
// reset the offset for the next data query
self.offset += self.itemsPerBatch
}
}
}
}
사하기더좋을 사용하는 것이 더 .willDisplayCell
로드 여부를 확인하는 방법입니다.일단 전류가 흐르면,indexPath.row
마지막으로 더 많은 셀을 로드할 수 있습니다.아래로 스크롤할 때 더 많은 셀이 로드됩니다.
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// check if indexPath.row is last row
// Perform operation to load new Cell's.
}
세부 사항
- Swift 5.1, X 코드 11.2.1
해결책
UIScrollView / UICollectionView / UITableView로 작업함
import UIKit
class LoadMoreActivityIndicator {
private let spacingFromLastCell: CGFloat
private let spacingFromLastCellWhenLoadMoreActionStart: CGFloat
private weak var activityIndicatorView: UIActivityIndicatorView?
private weak var scrollView: UIScrollView?
private var defaultY: CGFloat {
guard let height = scrollView?.contentSize.height else { return 0.0 }
return height + spacingFromLastCell
}
deinit { activityIndicatorView?.removeFromSuperview() }
init (scrollView: UIScrollView, spacingFromLastCell: CGFloat, spacingFromLastCellWhenLoadMoreActionStart: CGFloat) {
self.scrollView = scrollView
self.spacingFromLastCell = spacingFromLastCell
self.spacingFromLastCellWhenLoadMoreActionStart = spacingFromLastCellWhenLoadMoreActionStart
let size:CGFloat = 40
let frame = CGRect(x: (scrollView.frame.width-size)/2, y: scrollView.contentSize.height + spacingFromLastCell, width: size, height: size)
let activityIndicatorView = UIActivityIndicatorView(frame: frame)
if #available(iOS 13.0, *)
{
activityIndicatorView.color = .label
}
else
{
activityIndicatorView.color = .black
}
activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
activityIndicatorView.hidesWhenStopped = true
scrollView.addSubview(activityIndicatorView)
self.activityIndicatorView = activityIndicatorView
}
private var isHidden: Bool {
guard let scrollView = scrollView else { return true }
return scrollView.contentSize.height < scrollView.frame.size.height
}
func start(closure: (() -> Void)?) {
guard let scrollView = scrollView, let activityIndicatorView = activityIndicatorView else { return }
let offsetY = scrollView.contentOffset.y
activityIndicatorView.isHidden = isHidden
if !isHidden && offsetY >= 0 {
let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
let offsetDelta = offsetY - contentDelta
let newY = defaultY-offsetDelta
if newY < scrollView.frame.height {
activityIndicatorView.frame.origin.y = newY
} else {
if activityIndicatorView.frame.origin.y != defaultY {
activityIndicatorView.frame.origin.y = defaultY
}
}
if !activityIndicatorView.isAnimating {
if offsetY > contentDelta && offsetDelta >= spacingFromLastCellWhenLoadMoreActionStart && !activityIndicatorView.isAnimating {
activityIndicatorView.startAnimating()
closure?()
}
}
if scrollView.isDecelerating {
if activityIndicatorView.isAnimating && scrollView.contentInset.bottom == 0 {
UIView.animate(withDuration: 0.3) { [weak self] in
if let bottom = self?.spacingFromLastCellWhenLoadMoreActionStart {
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottom, right: 0)
}
}
}
}
}
}
func stop(completion: (() -> Void)? = nil) {
guard let scrollView = scrollView , let activityIndicatorView = activityIndicatorView else { return }
let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
let offsetDelta = scrollView.contentOffset.y - contentDelta
if offsetDelta >= 0 {
UIView.animate(withDuration: 0.3, animations: {
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}) { _ in completion?() }
} else {
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
completion?()
}
activityIndicatorView.stopAnimating()
}
}
사용.
안에
activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)
처리
extension ViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
activityIndicator.start {
DispatchQueue.global(qos: .utility).async {
sleep(3)
DispatchQueue.main.async { [weak self] in
self?.activityIndicator.stop()
}
}
}
}
}
전체 샘플
솔루션 코드를 붙여넣는 것을 잊지 마십시오.
import UIKit
class ViewController: UIViewController {
fileprivate var activityIndicator: LoadMoreActivityIndicator!
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: view.frame)
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "\(indexPath)"
return cell
}
}
extension ViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
activityIndicator.start {
DispatchQueue.global(qos: .utility).async {
for i in 0..<3 {
print("!!!!!!!!! \(i)")
sleep(1)
}
DispatchQueue.main.async { [weak self] in
self?.activityIndicator.stop()
}
}
}
}
}
결과
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
// This is the last cell
[self loadMore];
}
}
및 을 NSFetchedResultsController
,그리고나서loadMore
다음과 같이 표시될 수 있습니다.
// Load more
- (void)loadMore {
[self.fetchedResultsController.fetchRequest setFetchLimit:newFetchLimit];
[NSFetchedResultsController deleteCacheWithName:@"cache name"];
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
[self.tableView reloadData];
}
세부 사항
- Swift 5.1, Xcode 11.3.1
해결책
로드 추가를 위한 일반 UI 테이블 뷰 확장입니다.
새 파일에 이 UITableView + Extension 추가
extension UITableView {
func indicatorView() -> UIActivityIndicatorView{
var activityIndicatorView = UIActivityIndicatorView()
if self.tableFooterView == nil {
let indicatorFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 80)
activityIndicatorView = UIActivityIndicatorView(frame: indicatorFrame)
activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
if #available(iOS 13.0, *) {
activityIndicatorView.style = .large
} else {
// Fallback on earlier versions
activityIndicatorView.style = .whiteLarge
}
activityIndicatorView.color = .systemPink
activityIndicatorView.hidesWhenStopped = true
self.tableFooterView = activityIndicatorView
return activityIndicatorView
}
else {
return activityIndicatorView
}
}
func addLoading(_ indexPath:IndexPath, closure: @escaping (() -> Void)){
indicatorView().startAnimating()
if let lastVisibleIndexPath = self.indexPathsForVisibleRows?.last {
if indexPath == lastVisibleIndexPath && indexPath.row == self.numberOfRows(inSection: 0) - 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
closure()
}
}
}
}
func stopLoading() {
if self.tableFooterView != nil {
self.indicatorView().stopAnimating()
self.tableFooterView = nil
}
else {
self.tableFooterView = nil
}
}
}
이제 UITableViewDelegate 메서드에서 다음 코드 행을 추가하면 ViewController에 셀이 표시되고 테이블View.delegate = self가 표시됩니다.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// need to pass your indexpath then it showing your indicator at bottom
tableView.addLoading(indexPath) {
// add your code here
// append Your array and reload your tableview
tableView.stopLoading() // stop your indicator
}
}
결과
바로 그거야..이것이 도움이 되길 바랍니다.감사해요.
스택 오버플로에서 찾은 솔루션을 하나 구현했는데 작동이 잘 되지만, 신유엑스의 솔루션은 구현이 매우 쉽고 제 제안에도 잘 작동한다고 생각합니다.다른 솔루션을 원하는 사용자는 아래의 솔루션을 사용할 수 있습니다.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
// UITableView only moves in one direction, y axis
CGFloat currentOffset = scrollView.contentOffset.y;
CGFloat maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
//NSInteger result = maximumOffset - currentOffset;
// Change 10.0 to adjust the distance from bottom
if (maximumOffset - currentOffset <= 10.0) {
[self loadOneMorePage];
//[self methodThatAddsDataAndReloadsTableView];
}
}
쿼리에서 제한 및 간격띄우기를 사용하고 테이블 보기를 해당 내용으로 채웁니다.사용자가 아래로 스크롤하면 다음 오프셋을 로드합니다.
» tableView:willDisplayCell:forRowAtIndexPath:
의 의드에 .UITableViewDelegate
.
아래 링크는 샘플 코드를 제공합니다.#스위프트3
사용자는 서버에서 더 많은 데이터를 가져오려면 최소 2셀 높이의 마지막 테이블 보기 셀을 끌어올려야 합니다.
마지막 셀과 같이 로드 프로세스를 보여주는 프로세스 셀도 있습니다.
그것은 스위프트3에 있습니다.
https://github.com/yogendrabagoriya/YBTableViewPullData
한 가지 더 사용할 수 있는 옵션(Swift 3 및 iOS 10+):
class DocumentEventsTableViewController: UITableViewController, UITableViewDataSourcePrefetching {
var currentPage: Int = 1
let pageSize: Int = 10 // num of items in one page
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.prefetchDataSource = self
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
let upcomingRows = indexPaths.map { $0.row }
if let maxIndex = upcomingRows.max() {
let nextPage: Int = Int(ceil(Double(maxIndex) / Double(pageSize))) + 1
if nextPage > currentPage {
// Your function, which attempts to load respective page from the local database
loadLocalData(page: nextPage)
// Your function, which makes a network request to fetch the respective page of data from the network
startLoadingDataFromNetwork(page: nextPage)
currentPage = nextPage
}
}
}
}
다소 작은 페이지(~10개 항목)의 경우 테이블에 잘 스크롤될 몇 개의 항목이 있을 때까지 nextPage가 약 1-2개일 수 있으므로 1페이지와 2페이지의 데이터를 수동으로 추가할 수 있습니다.하지만 다음 페이지에서는 모두 잘 작동할 것입니다.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (news.count == 0) {
return 0;
} else {
return news.count + 1 ;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
@try {
uint position = (uint) (indexPath.row);
NSUInteger row = [indexPath row];
NSUInteger count = [news count];
//show Load More
if (row == count) {
UITableViewCell *cell = nil;
static NSString *LoadMoreId = @"LoadMore";
cell = [tableView dequeueReusableCellWithIdentifier:LoadMoreId];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:LoadMoreId];
}
if (!hasMoreLoad) {
cell.hidden = true;
} else {
cell.textLabel.text = @"Load more items...";
cell.textLabel.textColor = [UIColor blueColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
NSLog(@"Load more");
if (!isMoreLoaded) {
isMoreLoaded = true;
[self performSelector:@selector(loadMoreNews) withObject:nil afterDelay:0.1];
}
}
return cell;
} else {
NewsRow *cell = nil;
NewsObject *newsObject = news[position];
static NSString *CellIdentifier = @"NewsRow";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = topLevelObjects[0];
// Configure the cell...
}
cell.title.text = newsObject.title;
return cell;
}
}
@catch (NSException *exception) {
NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
}
return nil;
}
이 게시물에 대한 매우 좋은 설명.
http://useyourloaf.com/blog/2010/10/02/dynamically-loading-new-rows-into-a-table.html
단순합니다. 행을 표시하고 더 많은 항목을 로드하는 것보다 마지막 행을 추가하고 숨길 필요가 있습니다.
ios UITableViewDataSourcePrefetching을 선택해야 합니다.
class ViewController: UIViewController {
@IBOutlet weak var mytableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mytableview.prefetchDataSource = self
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
print("prefetchdRowsAtIndexpath \(indexPaths)")
}
func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {
print("cancelPrefetchingForRowsAtIndexpath \(indexPaths)")
}
}
- https://developer.apple.com/documentation/uikit/uitableviewdatasourceprefetching https://andreygordeev.com/2017/02/20/uitableview-prefetching/
Xcode 10.1의 경우 Swift 4.2
이 비디오는 정말 좋은 튜토리얼 같아요!
프로젝트 시작/완료: https://github.com/RobCanton/Swift-Infinite-Scrolling-Example
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableView:UITableView!
var fetchingMore = false
var items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initTableView()
}
func initTableView() {
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
let layoutGuide = view.safeAreaLayoutGuide
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
cell.textLabel?.text = "Item \(items[indexPath.row])"
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.height * 4 {
if !fetchingMore {
beginBatchFetch()
}
}
}
func beginBatchFetch() {
fetchingMore = true
print("Call API here..")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.50, execute: {
print("Consider this as API response.")
let newItems = (self.items.count...self.items.count + 12).map { index in index }
self.items.append(contentsOf: newItems)
self.fetchingMore = false
self.tableView.reloadData()
})
}
}
API에서 로딩하기 위해, 그것은 나에게 작동한다, Xcode10, swift 4.2 :
1- 새 Swift 파일을 만들고 다음과 같이 합니다.
//
// apiTVCController.swift
// ApiTestingTableView
//
// Created by Hooma7n on 4/7/19.
// Copyright © 2019 Hooma7n. All rights reserved.
//
import Foundation
import Alamofire
class apiget {
var tableData : [Datum] = []
var loadin : [Datum] = []
var testfortotal : Int?
func getfromapi(completionHandler : ((_ isSucess : Bool) -> Void)?) {
let url = "https://reqres.in/api/users?page=1"
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.responseJSON(completionHandler : { response in
switch response.result {
case .success(let data):
guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
let decoder = JSONDecoder()
guard let result = try? decoder.decode(Welcome.self, from: jsonData) else {return}
self.tableData = result.data ?? []
self.testfortotal = result.total ?? 0
completionHandler?(true)
// print(result)
case .failure(let error):
print(error)
}
})
}
var pagecounter : Int = 2
func loadmore(completionHandler : ((_ isSucess : Bool) -> Void)?){
let url = "https://reqres.in/api/users?page=\(pagecounter)"
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.responseJSON(completionHandler : { response in
switch response.result {
case .success(let data):
guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
let decoder = JSONDecoder()
guard let myresult = try? decoder.decode(Welcome.self, from: jsonData) else {return}
self.loadin = myresult.data ?? []
self.tableData.append(contentsOf: myresult.data ?? [])
completionHandler?(true)
print(self.pagecounter)
self.pagecounter += 1
// print(myresult)
case .failure(let error):
print(error)
}
})
}
}
extension apiget {
struct Welcome: Codable {
let page, perPage, total, totalPages: Int?
var data: [Datum]?
enum CodingKeys: String, CodingKey {
case page
case perPage = "per_page"
case total
case totalPages = "total_pages"
case data
}
}
struct Datum: Codable {
let id: Int?
let firstName, lastName: String?
let avatar: String?
enum CodingKeys: String, CodingKey {
case id
case firstName = "first_name"
case lastName = "last_name"
case avatar
}
}
}
2- ViewController 파일(테이블 ViewController):
//
// apiTVC.swift
// ApiTestingTableView
//
// Created by Hooma7n on 4/7/19.
// Copyright © 2019 Hooma7n. All rights reserved.
//
import UIKit
import Alamofire
class apiTVC: UITableViewController {
var datamodel = apiget()
override func viewDidLoad() {
super.viewDidLoad()
datamodel.getfromapi(completionHandler: {finish in
if finish {self.tableView.reloadData()
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datamodel.tableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! apiTableViewCell
cell.firstNameLabel.text = datamodel.tableData[indexPath.row].firstName
cell.lastNameLabel.text = datamodel.tableData[indexPath.row].lastName
cell.dateLabel.text = "\(datamodel.tableData[indexPath.row].id ?? 0)"
cell.profileImageView.loadImage(fromURL: datamodel.tableData[indexPath.row].avatar ?? "")
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastElement = datamodel.tableData.count - 1
let total = datamodel.testfortotal ?? 12
if indexPath.row == lastElement && datamodel.tableData.count < total{
datamodel.loadmore(completionHandler: {finish in
if finish {
self.tableView.reloadData()
}})
}
}
}
tableView를 사용하는 경우에는 ViewController set delegate, viewDidLoad의 데이터 원본 자체를 사용합니다.
이 접근 방식을 공유하고 싶습니다.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@"%@", [[YourTableView indexPathsForVisibleRows] lastObject]);
[self estimatedTotalData];
}
- (void)estimatedTotalData
{
long currentRow = ((NSIndexPath *)[[YourTableView indexPathsForVisibleRows] lastObject]).row;
long estimateDataCount = 25;
while (currentRow > estimateDataCount)
{
estimateDataCount+=25;
}
dataLimit = estimateDataCount;
if (dataLimit == currentRow+1)
{
dataLimit+=25;
}
NSLog(@"dataLimit :%ld", dataLimit);
[self requestForData];
// this answers the question..
//
if(YourDataSource.count-1 == currentRow)
{
NSLog(@"LAST ROW"); //loadMore data
}
}
NSLog(...);
출력은 다음과 같습니다.
<NSIndexPath: 0xc0000000002e0016> {length = 2, path = 0 - 92}
dataLimit :100
<NSIndexPath: 0xc000000000298016> {length = 2, path = 0 - 83}
dataLimit :100
<NSIndexPath: 0xc000000000278016> {length = 2, path = 0 - 79}
dataLimit :100
<NSIndexPath: 0xc000000000238016> {length = 2, path = 0 - 71}
dataLimit :75
<NSIndexPath: 0xc0000000001d8016> {length = 2, path = 0 - 59}
dataLimit :75
<NSIndexPath: 0xc0000000001c0016> {length = 2, path = 0 - 56}
dataLimit :75
<NSIndexPath: 0xc000000000138016> {length = 2, path = 0 - 39}
dataLimit :50
<NSIndexPath: 0xc000000000120016> {length = 2, path = 0 - 36}
dataLimit :50
<NSIndexPath: 0xc000000000008016> {length = 2, path = 0 - 1}
dataLimit :25
<NSIndexPath: 0xc000000000008016> {length = 2, path = 0 - 1}
dataLimit :25
로컬로 저장된 데이터를 표시하는 데 유용합니다.처음에 dataLimit을 25로 선언합니다. 즉, 적합한 보기가 0-24(초기)입니다.
사용자가 맨 아래로 스크롤하여 마지막 셀을 볼 수 있는 경우dataLimit
25를 더하면...
참고: 이는 UITableView 데이터 페이징에 더 가깝습니다. :)
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger sectionsAmount = [tableView numberOfSections];
NSInteger rowsAmount = [tableView numberOfRowsInSection:[indexPath section]];
if ([indexPath section] == sectionsAmount - 1 && [indexPath row] == rowsAmount - 1) {
//get last row
if (!isSearchActive && !isFilterSearchActive) {
if (totalRecords % 8 == 0) {
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
[yourTableView beginUpdates];
[yourTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[yourTableView endUpdates];
});
}
}
}
}
이 문제를 해결하는 가장 좋은 방법은 표의 맨 아래에 셀을 추가하는 것이며 이 셀은 표시기를 고정합니다.
신속하게 다음 사항을 추가해야 합니다.
- Create of type cell(셀 유형의 새 셀 만들기)로딩됩니다.아래 코드를 보십시오.
- 행 수를 보고 1을 추가합니다(이것은 로드 셀용입니다).
- rawAt를 체크인해야 합니다.idexPath.row == yourArray.count인 경우 인덱싱한 다음 Loading 셀을 반환합니다.
아래 코드를 확인하십시오.
import UIKit
class LoadingCell: UITableViewCell {
@IBOutlet weak var indicator: UIActivityIndicatorView!
}
테이블 뷰: numOfRows:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourArray.count + 1
}
cellForRawAt indexPath:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == users.count {
// need to change
let loading = Bundle.main.loadNibNamed("LoadingCell", owner: LoadingCell.self , options: nil)?.first as! LoadingCell
return loading
}
let yourCell = tableView.dequeueReusableCell(withIdentifier: "cellCustomizing", for: indexPath) as! UITableViewCell
return yourCell
}
내 로딩 셀이 nib 파일에서 생성된 것을 당신이 알아차린다면요.이 비디오들은 제가 한 일을 설명해 줄 것입니다.
let threshold = 100.0 // threshold from bottom of tableView
var isLoadingMore = false // flag
func scrollViewDidScroll(scrollView: UIScrollView) {
let contentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
if !isLoadingMore && (maximumOffset - contentOffset <= threshold) {
// Get more data - API call
self.isLoadingMore = true
// Update UI
dispatch_async(dispatch_get_main_queue()) {
tableView.reloadData()
self.isLoadingMore = false
}
}
}
샘플 코드입니다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ShowComplainCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! ShowComplainCell
let item = self.dataArray[indexPath.row] as! ComplainListItem;
let indexPathArray = NSArray(array: tableView.indexPathsForVisibleRows!)
let vIndexPath = indexPathArray.lastObject as! NSIndexPath
let lastItemReached = item.isEqual(self.dataArray.lastObject);
if (lastItemReached && vIndexPath.row == (self.dataArray.count - 1))
{
self.loadData()
}
return cell
}
indexPathArray: 행이 표시됩니다.
vIndexPath: 마지막 인덱스 경로가 표시됨
데이터 로드
func loadData(){
if(isReloadTable){
let HUD = MBProgressHUD.showAdded(to: self.view, animated: true)
let manager :AFHTTPSessionManager = AFHTTPSessionManager()
var param = NSDictionary()
param = [
"category":cat_id,
"smart_user_id": USERDEF.value(forKey: "user_id") as! String,
"page":page,
"phone":phone! as String
] as [String : Any] as NSDictionary
print("param1 = \(param)")
manager.get("lists.php?", parameters: param, progress: nil, success: { (task:URLSessionDataTask, responseObject: Any) in
let adsArray = dic["results"] as! NSArray;
for item in adsArray {
let item = ComplainListItem(dictionary: item as! NSDictionary )
self.dataArray.add(item)
}
self.view.addSubview(self.cityTableView)
self.cityTableView.reloadData()
if(adsArray.count==10){
self.cityTableView.reloadData()
self.isReloadTable = true
self.page+=1
}else if(adsArray.count<10){
self.cityTableView.reloadData()
self.isReloadTable = false
}
HUD.hide(animated:true)
}) { (operation,error) -> Void in
print("error = \(error)")
HUD.hide(animated:true)
}
}
}
데이터를 확인합니다. 데이터 제한과 동일한 myadsarray 검사인 어레이 수를 확인합니다.그런 다음 dataArray count equal next 페이지가 호출되면 10보다 작지 않으면 모든 데이터가 표시되거나 완료됩니다.
언급URL : https://stackoverflow.com/questions/20269474/uitableview-load-more-when-scrolling-to-bottom-like-facebook-application
'sourcecode' 카테고리의 다른 글
SQL Server 2005의 교착 상태 진단 (0) | 2023.07.08 |
---|---|
프로필을 spring.profiles.include로 포함하면 include 대신 재정의되는 것 같습니다. (0) | 2023.07.08 |
Vue에서 동적 v-model 이름 바인딩을 수행하는 방법 (0) | 2023.07.08 |
Python datetime 객체에서 연도를 추출하는 방법은 무엇입니까? (0) | 2023.07.08 |
SQL 조인 하위 쿼리 (0) | 2023.07.08 |