Loading an Array to TableView based on Segment-Control - ios

I am relatively new to Swift. I tried to search and google the problem but i can't find any answers. It shouldn't be that hard. Hope you guys can help me out. I‘ve been struggling with this Issue over days now:
I created a Tableview which loads an array of tuples from another .swift file. That is working fine! Now I want the tableview to choose the .swift based on a "segment control". So if the Segment-Control is switched to "A" I want it to show the Array of "PSSCBOOKMac.Swift", for B it would be the Array of "PSSCBOOKWin.swift".
The Action ist written properly, I guess (print-statements are working). But the change of the segment-control doesn't effect the Tableview. My guess: The segment-control doesn't effect the Tableview because it has been loaded before and I can't change the value. How can I achieve that?
Cheers for any answers!
Here is the Code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet weak var PSSCSegmentControl: UISegmentedControl!
//LOAD ARRAY FROM PSSCBOOK.SWIFT
var PSSCBook = PSSCBOOKMac()
#IBAction func PSSCSegmentControlChoose(sender: AnyObject) {
if PSSCSegmentControl.selectedSegmentIndex == 0 {
var PSSCBook = PSSCBOOKMac()
println("im mac")
} else {
var PSSCBook = PSSCBOOKWin()
println("im win")
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return PSSCBook.PSSCTools.count
} else {
return PSSCBook.PSSCFile.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("PSCell", forIndexPath: indexPath) as! UITableViewCell
if indexPath.section == 0 {
let (shortCutTitle,shortCutKey) = PSSCBook.PSSCTools[indexPath.row]
cell.textLabel?.text = shortCutTitle
cell.detailTextLabel?.text = shortCutKey
} else {
let (shortCutTitle,shortCutKey) = PSSCBook.PSSCFile[indexPath.row]
cell.textLabel?.text = shortCutTitle
cell.detailTextLabel?.text = shortCutKey
}
/* var PSIcon = UIImage(named: "PSIcon")
cell.imageView?.image = PSIcon */
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Tools"
} else {
return "File"
}
}
}

When you update the datasource of your table view, it won't magically update itself.
You have to reload the table view for the changes to take place:
#IBAction func PSSCSegmentControlChoose(sender: AnyObject) {
if PSSCSegmentControl.selectedSegmentIndex == 0 {
var PSSCBook = PSSCBOOKMac()
println("im mac")
} else {
var PSSCBook = PSSCBOOKWin()
println("im win")
}
self.tableView.reloadData();
}

I spend the last two days trying to figure out what was wrong with my code. I implemented the suggested reloadData() without having errors. The println Values in the console change.. But the tableview just won't refresh. I really don’t know where else to look, is searched for hours. Could somebody please tell me what type of silly mistake I am doing? Thanks guys!
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
//LOAD ARRAY FROM PSSHORTCUTSBOOK.SWIFT
var PSSCBook = PSShortCutsBook()
#IBOutlet weak var SCOutlet: UISegmentedControl!
#IBOutlet weak var SCtableviewOutlet: UITableView!
#IBAction func SCAction(sender: AnyObject) {
if SCOutlet.selectedSegmentIndex == 1 {
var PSSCBook = PSShortCutsBook()
println("There are \(PSSCBook.shortCutsPS.count) items in this Array")
self.SCtableviewOutlet.reloadData();
} else {
var PSSCBook = PSShortCutsBook2()
println("There are \(PSSCBook.shortCutsPS.count) items in this Array")
self.SCtableviewOutlet.reloadData();
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return PSSCBook.shortCutsPS.count
} else {
return PSSCBook.shortCutsPS2.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("PSCell", forIndexPath: indexPath) as! UITableViewCell
if indexPath.section == 0 {
let (shortCutTitle,shortCutKey) = PSSCBook.shortCutsPS[indexPath.row]
cell.textLabel?.text = shortCutTitle
cell.detailTextLabel?.text = shortCutKey
} else {
let (shortCutTitle,shortCutKey) = PSSCBook.shortCutsPS2[indexPath.row]
cell.textLabel?.text = shortCutTitle
cell.detailTextLabel?.text = shortCutKey
}
/* var PSIcon = UIImage(named: "PSIcon")
cell.imageView?.image = PSIcon */
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Tools"
} else {
return "Help"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

Call function from UITableViewCell from in ViewController Swift

I need to call function deleteButtonShowHide, which is in TeamsCell, from TeamsVC, when plusBtnTapped. I am trying to figure it out with protocol TeamsVCDelegate, but it doesn't work( It works vice versa for me. But I do not know how to implement something like cell.teamsCellDelegate = self
TeamsCell
import UIKit
protocol TeamsCellDelegate {
func deleteCell()
}
class TeamsCell: UITableViewCell {
#IBOutlet weak var teamNameLbl: UILabel!
#IBOutlet weak var deleteButton: UIButton!
var teamsCellDelegate: TeamsCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func updateCell(team: team) {
teamNameLbl.text = team.name
}
#IBAction func deleteButtonTapped(_ sender: Any) {
debugPrint("delet tapped")
//deleteButtonShowHide()
findAndDeleteTeam()
teamsCellDelegate?.deleteCell()
}
func findAndDeleteTeam() {
for i in 0...teams.count - 1 {
if teams[i].name == teamNameLbl.text {
teams.remove(at: i)
break
}
}
}
func deleteButtonShowHide(){
if teams.count < 3 {deleteButton.isHidden = true}
if teams.count > 2 {deleteButton.isHidden = false}
}
}
extension TeamsCell: TeamsVCDelegate {
func deleteButtonSH() {
debugPrint("XXX")
deleteButtonShowHide()
}
}
TeamsVC
import UIKit
protocol TeamsVCDelegate {
func deleteButtonSH()
}
class TeamsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var plusBtn: UIButton!
#IBOutlet weak var teamsTable: UITableView!
var teamsVCDelegate: TeamsVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
teamsTable.delegate = self
teamsTable.dataSource = self
teamsTable.rowHeight = 55
teamsTable.isScrollEnabled = false
teamsTable.backgroundColor = nil
teamsTable.separatorStyle = .none
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
#IBAction func plusBtnTapped(_ sender: Any) {
plusBtnHide()
addTeam()
teamsTable.reloadData()
teamsVCDelegate?.deleteButtonSH()
print(teams)
}
func plusBtnShow() {
if teams.count < 5 {plusBtn.isHidden = false}
}
func plusBtnHide() {
if teams.count == 4 { plusBtn.isHidden = true}
}
}
extension TeamsVC: TeamsCellDelegate {
func deleteCell() {
self.teamsTable.reloadData()
self.plusBtnShow()
}
}
You could call deleteButtonShowHide function when you are loading/setting up a cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.deleteButtonShowHide() // <-- HERE
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
By the way, your cell should not contain such logic in the first place. It should depend on some data model object which then should be used to setup your cell correctly (show/hide UI elements, etc.).
You could simplify by setting the button show/hide when computing the number of row.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if teams.count < 5 {plusBtn.isHidden = false}
if teams.count == 4 { plusBtn.isHidden = true}
return teams.count
}
And set the delebutton visibility when creating the cell :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
// cell.teamsCellDelegate = self
cell.deleteButton.isHidden = (teams.count < 3)
return cell
}
return UITableViewCell()
}
So no need for delegate and cell does not have to know about the model (teams)

Single table view through two different NSFetchedResultsControllers with sections

Good morning to everyone. I am using Swift 3.1.1, Xcode 8.3.2. I need to connect a single Table View to two different tables (entities) in Core Data through two different NSFetchedResultsControllers. I have created two NSFetchedResultsControllers, and even fetched data from table but I faced problem how to tell Table View that first controller should response for section one and second controller should be responsible for section two.
I can show you the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tv: UITableView!
#IBAction func pressed(_ sender: UIButton) {
ModelA.read { table1 in
ModelB.read { table2 in
if table1.isEmpty {
ModelA.save(recordToSave: [(a: 1, b: "a"), (a: 2, b: "b"), (a: 3, b: "c")]) {
ModelB.save(recordToSave: [(a: 4, b: 5.0, c: true), (a: 6, b: 7.0, c: false)]) {
self.tvReload()
}
}
} else {
self.tvReload()
}
}
}
}
var fetchedResultsControllerForModelA = CoreDataFunctions.fetchedResultsController
var fetchedResultsControllerForModelB = CoreDataFunctions.fetchedResultsController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tvReload()
}
func modelOfTableA(indexPath: IndexPath) -> (forLabel1: String, forLabel2: String, forLabel3: String)? {
if let fetchedResultsControllerForModelA = CoreDataFunctions.getNSManagedObjectForIndexPathOfTable(fetchedResultsController: fetchedResultsControllerForModelA, indexPath: indexPath) {
if let model = ModelA.read(nsmanagedobject: fetchedResultsControllerForModelA) {
return (forLabel1: "\(model.a)", forLabel2: model.b, forLabel3: "")
}
}
return nil
}
func modelOfTableB(indexPath: IndexPath) -> (forLabel1: String, forLabel2: String, forLabel3: String)? {
if let fetchedResultsControllerForModelB = CoreDataFunctions.getNSManagedObjectForIndexPathOfTable(fetchedResultsController: fetchedResultsControllerForModelB, indexPath: indexPath) {
if let model = ModelB.read(nsmanagedobject: fetchedResultsControllerForModelB) {
return (forLabel1: "\(model.a)", forLabel2: "\(model.b)", forLabel3: "\(model.c)")
}
}
return nil
}
func tvReload() {
fetchedResultsControllerForModelA = CoreDataFunctions(tableName: .a).fetchedResultsController(keyForSort: ModelA.a.rawValue, searchParameters: nil)
fetchedResultsControllerForModelB = CoreDataFunctions(tableName: .b).fetchedResultsController(keyForSort: ModelB.a.rawValue, searchParameters: nil)
do {
try fetchedResultsControllerForModelA?.performFetch()
try fetchedResultsControllerForModelB?.performFetch()
DispatchQueue.main.async {
self.tv.reloadData()
}
} catch {
print("Error")
}
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections1 = fetchedResultsControllerForModelA?.sections {
if let sections2 = fetchedResultsControllerForModelB?.sections {
return sections1[section].numberOfObjects + sections2[section].numberOfObjects
}
return sections1[section].numberOfObjects
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
if indexPath.section == 0 {
if let modelOfTable = modelOfTableA(indexPath: indexPath) {
cell.l1.text = modelOfTable.forLabel1
cell.l2.text = modelOfTable.forLabel2
cell.l3.text = modelOfTable.forLabel3
}
} else {
if let modelOfTable = modelOfTableB(indexPath: indexPath) {
cell.l1.text = modelOfTable.forLabel1
cell.l2.text = modelOfTable.forLabel2
cell.l3.text = modelOfTable.forLabel3
}
}
return cell
}
}
I could not find any tutorial on this theme, so I am asking question there. I do not want to use inheritance from single entity in Core Data, because, in real life it would be impossible.
Thank you for any help or advice!
OK - I downloaded your code, and there are a couple issues...
1) If you want your data to fill two sections in the table, the table must have two sections - currently, you are just returning 1, so use this (although you may want/need different handling based on data retrieved):
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
if fetchedResultsControllerForModelA == nil || fetchedResultsControllerForModelB == nil {
return 0
}
return 2
}
2) For number of rows in each section, your code was close but not quite right...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if let sections = fetchedResultsControllerForModelA?.sections {
return sections[0].numberOfObjects
}
} else {
if let sections = fetchedResultsControllerForModelB?.sections {
return sections[0].numberOfObjects
}
}
return 0
}
3) For the actual cellForRowAtIndexPath data, again your code was close but you need to keep track of which data to get for each section...
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
if indexPath.section == 0 {
if let modelOfTable = modelOfTableA(indexPath: indexPath) {
cell.l1.text = modelOfTable.forLabel1
cell.l2.text = modelOfTable.forLabel2
cell.l3.text = modelOfTable.forLabel3
}
} else {
// Each "Table data model" has only one section... since this is the 2nd table section, we need
// to change the section of the index path for our call to the data model
let dataIndexPath = IndexPath(row: indexPath.row, section: 0)
if let modelOfTable = modelOfTableB(indexPath: dataIndexPath) {
cell.l1.text = modelOfTable.forLabel1
cell.l2.text = modelOfTable.forLabel2
cell.l3.text = modelOfTable.forLabel3
}
}
return cell
}
That should get you on your way.

TableView not loading cells

My table view isn't loading the custom cells that are put into an array when I do a certain function. I know the the array contains the cells, but am at a loss as to why the cells aren't showing. It did work before but I made a few changes elsewhere in the code and now it does not work. Below is the code where I believe the error might possibly be:
#IBOutlet weak var incomeExpenseTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
incomeExpenseTableView.reloadData()
incomeExpenseTableView.delegate = self
incomeExpenseTableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
incomeExpenseTableView.reloadData()
}
#IBAction func addButtonPressed(sender: AnyObject) {
let addMessage = SCLAlertView()
addMessage.addButton("Income") {
self.performSegueWithIdentifier("incomeSegue", sender: self)
}
addMessage.addButton("Expense") {
self.performSegueWithIdentifier("expenseSegue", sender: self)
}
addMessage.showInfo("New Entry", subTitle: "Select either an income or expense to add")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = DATA_KEY._loadedPosts[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as? IncomeExpenseCell {
cell.configureCell(post)
return cell
} else {
let cell = IncomeExpenseCell()
cell.configureCell(post)
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataService.instance._loadedPosts.count
}
func onPostsLoaded(notif: AnyObject) {
incomeExpenseTableView.reloadData()
}
FYI DATA_KEY = DataService.instance
Thanks
if you have a tableviewcell's identifier named "IncomeExpenseCell", the "if let" will always be successful, why using else, you can use as! instead of as?, you don't need 'else' here, and IncomeExpenseCell() maybe will not satisfy your 'cell init'
if let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as? IncomeExpenseCell {
cell.configureCell(post)
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier("IncomeExpenseCell") as! IncomeExpenseCell {
cell.configureCell(post)
return cell
}

Load more options with UITableView

Trying to load my data in page using pagination, I've already seen many examples but all are in Objective-C and some questions are unanswered.
My code:
class testTableViewController: UITableViewController {
//MARK: - Properties -
var allObjectArray: NSMutableArray = []
var elements: NSMutableArray = []
var currentPage = 0 //number of current page
var nextpage = 0
var selectedRow = Int()
//MARK: - View Life Cycle -
override func viewDidLoad() {
super.viewDidLoad()
for var i = 1; i < 500; i++ {
allObjectArray.addObject(i)
}
elements.addObjectsFromArray(allObjectArray.subarrayWithRange(NSMakeRange(0, 30)))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source -
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count + 1
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedRow = (tableView.indexPathForSelectedRow?.row)!
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var customCell = tableView.dequeueReusableCellWithIdentifier("cell")
customCell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
customCell!.textLabel!.text = "cell - \(allObjectArray[indexPath.row])"
if indexPath.row == elements.count {
customCell?.textLabel?.textColor = UIColor.blueColor()
customCell?.textLabel?.text = "Load more..."
}
return customCell!
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
nextpage = elements.count
if indexPath.row == nextpage {
if indexPath.row == selectedRow {
currentPage++
nextpage = elements.count - 5
elements.addObjectsFromArray(allObjectArray.subarrayWithRange(NSMakeRange(currentPage, 30)))
tableView.reloadData()
}
}
}
}
I want this kind of output:
Tried to fetch selected index but it will return nil.
Create Outlets in Interface Builder for tableview and make two dynamic prototype cells give them identifiers make one cell with a button(your load more cell button)
Then create action with that button that will contain the logic to load more cells!!!
now see the snipet below for reference...
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tblDemo: UITableView!
var arForCells:NSMutableArray = NSMutableArray()
let simpleCellID = "SimpleCell"
let loadMoreCell = "LoadMoreCell"
override func viewDidLoad() {
super.viewDidLoad()
tblDemo.delegate = self
tblDemo.dataSource = self
arForCells = NSMutableArray(objects: "1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arForCells.count + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == arForCells.count){
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(loadMoreCell, forIndexPath: indexPath)
return cell
}else {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(simpleCellID, forIndexPath: indexPath)
let lblCounter = cell.viewWithTag(111) as! UILabel
lblCounter.text = arForCells.objectAtIndex(indexPath.row) as! String
return cell
}
}
#IBAction func loadMoreCells(sender: AnyObject) {
let newAr:NSArray = NSArray(objects: "1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
arForCells.addObjectsFromArray(newAr as [AnyObject])
tblDemo.reloadData()
}}
as I have checked, It should give you the desired results.
You could also do the same in TableViewFooter.
To set "Load More.." text add a label with this text in a view having the same size of your tableViewCell. Then add this in your tableView footer. Add a (custom/transparent)button in footer view so when that touched it will load your main array with more data and then reload your tableView.
Hope this helps!
First of all, You don't have to use this:
selectedRow = (tableView.indexPathForSelectedRow?.row)!
in the didSelectRowAtIndexPath. You can use simply
selectedRow = indexPath.row
next, your logic for willDisplayCellAtIndexPath seems redundant if you want to have cell to tap on it. You can simply put the following in enter code here:
nextpage = elements.count
if indexPath.row == nextpage {
currentPage++
nextpage = elements.count - 5
elements.addObjectsFromArray(allObjectArray.subarrayWithRange(NSMakeRange(currentPage, 30)))
tableView.reloadData()
}
also, I am not sure why do you need nextpage = elements.count - 5 but I assume that you have reason behind this.
done it my self
import UIKit
class LoadMoreTableVC: UITableViewController {
//MARK: - Properties -
var allObjectArray: NSMutableArray = []
var elements: NSMutableArray = []
var currentPage = 0 //number of current page
var nextpage = 0
var totalElements = 500 //total elements
var elementAtOnePage = 30 //at one page
//MARK: - View Life Cycle -
override func viewDidLoad() {
super.viewDidLoad()
for i in 0 ..< totalElements {
allObjectArray.addObject(i+1)
}
elements.addObjectsFromArray(allObjectArray.subarrayWithRange(NSMakeRange(0, elementAtOnePage)))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source -
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = elements.count + 1
if count < allObjectArray.count
{
return count
}
else
{
return allObjectArray.count
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == elements.count {
loadDataDelayed()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel!.text = "\(allObjectArray[indexPath.row])"
if indexPath.row == elements.count {
cell.textLabel?.text = "Load more..."
}
return cell
}
func loadDataDelayed(){
currentPage += 1
elements.addObjectsFromArray(allObjectArray.subarrayWithRange(NSMakeRange(currentPage, elementAtOnePage)))
tableView.reloadData()
}
}
I have already done this is in swift.
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if loading == true {
var endScrolling:CGFloat = scrollView.contentOffset.y + scrollView.frame.size.height
if(endScrolling >= scrollView.contentSize.height){
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "loadDataDelayed", userInfo: nil, repeats: false)
}
}
}
Please try this code.
And share your response.
Happy coding :)

ImagesTabViewController' does not conform to protocol 'UITableViewDataSource'

I know this question has been asked a million times, but I can't find a resolution to this specific issue. I'm using Xcode 6.3 beta 4 with Swift 1.2 and since the last update I haven't been able to get a regular UITableView with the supporting datasource and delegate protocols working.
I am getting the above error and "Definition conflicts with previous value" for the numberOfRowsInSection function. At this point I don't know if it's a Swift change or I am missing something. The tableview is connected properly..
Thanks for any help.
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}}
There is a bracket missing and didReceiveMemoryWarning must be overridden. Here is the revised code:
class ImagesTabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var collectionInfo: NSArray = DataManager.getUserCollections()
var items: NSMutableArray = []
var namesArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
APIManager().getData() { completed in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completed {
self.collectionInfo = DataManager.getUserCollections()
var collectionNames: AnyObject = self.collectionInfo[3]
println(collectionNames)
self.items = NSMutableArray(array: self.collectionInfo)
} else {
//do something else
}
})
// Do any additional setup after loading the view.
}
} // <- Was missing!
// Override!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var collectionsAndArrays = PSCollection()
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Configure the cell...
collectionsAndArrays = self.items[indexPath.row] as! PSCollection
cell.textLabel!.text = collectionsAndArrays.name
cell.detailTextLabel!.text = collectionsAndArrays.created_at
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfCollections: Int = self.items.count
return numberOfCollections
}
}

Resources