Swift Table View Reload Creating Cell Instance Again
Today's topic we will hash out the Pull to Refresh in Swift, or you tin say UIRefresh Control.
UIRefersh Control inherits from UIControl. In improver, UIControl inherits from the UIView and UIView inherits from the UIResponder.
Finally, UIResponder inherits from the NSObject class.
Nosotros can use UIRefresh Control with whatever UIScrollView objects like UITableview or UICollectionView.
We will bear witness how to use UIRefresh Control when nosotros pull downward the UIScrollView object and refresh its content.
Pull to Refresh in Swift
UI Implementation for Pull to Refresh in Swift:
We are going to implement the Pull to Refresh functionality by calling an API and populating the table view with the data returned from the API.
one. Let'due south begin by creating an Xcode project, adding a tabular array view and a label in the Main storyboard.
2. Create TableViewCell and Xib. Later that, annals TableViewCell and assign consul and dataSource.
iii. Table view cell is populated with the information returned by the API call
Calculation basic functionality for Pull to Refresh in Swift:
i. Create a model to parse the data equally beneath. Afterward that, we volition decode the API response using JSONDecoder.
struct DataResponse : Codable { var results : DataResult } struct DataResult : Codable { var sunrise : String var sunset : String var day_length : Int } |
2. Till at present, your viewDidLoad() function would look like beneath.
override func viewDidLoad ( ) { super . viewDidLoad ( ) // annals tableview cell self . tableView . annals ( UINib ( nibName : "TableViewCell" , parcel : null ) , forCellReuseIdentifier : "TableViewCell" ) tableView . delegate = self tableView . dataSource = self tableView . tableFooterView = UIView ( ) } |
3. Create a variable array to store the desired values. For instance, we accept created var apiInformation = [String]()
4. After that, we will create a office fetchAPIData() for the network-related task. This part is chosen from the viewDidLoad().
ane 2 3 4 5 half-dozen seven viii 9 x 11 12 thirteen 14 15 16 17 xviii 19 20 21 22 | func fetchAPIData ( ) { self . apiData . removeAll ( ) guard let url = URL ( cord : "https://api.sunrise-sunset.org/json?date=2021-6-20&lng=77.3910&lat=28.5355&formatted=0" ) else { render } // network job created an API is being called let task = URLSession . shared . dataTask ( with : url , completionHandler : { data , _ , mistake in guard let information = information , mistake == zippo else { return } var dataResult : DataResponse ? practise { // decoding the response to the model DataResponse dataResult = try JSONDecoder ( ) . decode ( DataResponse . cocky , from : data ) } catch { print ( error . localizedDescription ) } guard allow finalDataResult = dataResult else { render } // storing the data to the divers array apiData of type Cord cocky . apiData . append ( "Sunrise: \ ( finalDataResult . results . sunrise )" ) self . apiData . append ( "Sunset: \ ( finalDataResult . results . sunset )" ) cocky . apiData . append ( "Mean solar day length: \ ( finalDataResult . results . day_length )" ) } ) task . resume ( ) } |
five. In the above lawmaking nosotros are hitting the API and decoding the returned information to DataModel DataResponse using Codable protocol.
6. We are then appending the data to apiData array of type String. We will now populate our TableView with the data of the apiData array, shown beneath.
func tableView ( _ tableView : UITableView , numberOfRowsInSection section : Int ) -> Int { render apiData . count } func tableView ( _ tableView : UITableView , cellForRowAt indexPath : IndexPath ) -> UITableViewCell { let cell = tableView . dequeueReusableCell ( withIdentifier : "TableViewCell" , for : indexPath ) as ! TableViewCell cell . celllabel . text = self . apiData [ indexPath . row ] return jail cell } func tableView ( _ tableView : UITableView , heightForRowAt indexPath : IndexPath ) -> CGFloat { render l } |
Calculation UIRefreshControl
Till at present we prepared our ViewController course to use the UIRefreshControl which will be visible when nosotros pull down our Tabular array view.
UIRefreshControl will start working when the user pulls the Tableview, it will call the fetchAPIData() function and reloads the tabular array view with new data returned from the API.
refreshControl will telephone call the objective-C office callPullToRefresh based on its value changes through the listener .valueChanged
Later that, add the below code to your viewDidLoad()
// initializing the refreshControl tableView . refreshControl = UIRefreshControl ( ) // add target to UIRefreshControl tableView . refreshControl ? . addTarget ( cocky , action : #selector(callPullToRefresh), for: .valueChanged) |
Now declare an objective-C function which will call the fetchAPIData() function.
@ objc func callPullToRefresh ( ) { self . fetchAPIData ( ) } |
In addition to the above, we must update our UI in the main thread. Therefore, use the beneath code later on the network call in fetchAPIData() function.
DispatchQueue . master . asyncAfter ( deadline : . now ( ) + 5 ) { self . tableView . refreshControl ? . endRefreshing ( ) self . refreshLabel . isHidden = true cocky . tableView . reloadData ( ) } |
endRefreshing() function tells the condition of the UIRefreshControl that it has finished refreshing the UITableView. Similarly, beginRefreshing() tells the condition of the UIControl is now started refreshing the contents.
In the higher up code, nosotros have made a filibuster of 5 seconds for refreshControl. The refreshControl volition be visible for five seconds.
Accordingly, we are hiding and unhiding the refreshLabel.
We are updating the refreshLabel in the below code within the fetchAPIData()
if tableView . refreshControl ? . isRefreshing == true { self . refreshLabel . isHidden = simulated self . refreshLabel . text = "Refreshing..." } else { print ( "Calling API" ) } |
isRefreshing is a boolean belongings that describes the current country of the UIRefreshControl
Based on the isRefreshing value we are updating the refreshLabel status.
Now your fetchAPIData() part would like as shown in the beneath image.
Result
After successfully adding the UIRefreshControl, your app volition wait similar below.
Conclusion
Here, we take used the custom refreshLabel to show the refreshing status of the UIRefreshControl notwithstanding, yous tin utilise the UIRefreshControl aspect attributedTitle for showing the status of the UIRefreshControl.
Yous can likewise bank check the Apple documentation for UIRefreshControl here
We hope this blog will help you in creating interactive designs for your projects.
For other blogs Please click here
. . .
Source: https://mobikul.com/pull-to-refresh-in-swift/
0 Response to "Swift Table View Reload Creating Cell Instance Again"
Post a Comment