Data loading from core data to table very slowly - ios

I have table in core data with 100 rows, in tableView I load filtered 25 rows. When I open this UIViewController in app it take near 2 seconds, I think it is very slowly. I test my app on iPhone 5. May be I do something wrong?
I see that cellForRowAtIndexPath method call 4 times for all rows: 1-25, then again 1-25 etc. Is it ok?
When I load just 1 row it works fast.
class TipsViewController: UIViewController, UITableViewDelegate
{
#IBOutlet weak var tableView: UITableView!
var tips = [Tips]()
lazy var managedObjectContext : NSManagedObjectContext? =
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext
{
return managedObjectContext
}
else {
return nil
}
}()
let defaults = NSUserDefaults.standardUserDefaults()
var languge:String!
override func viewDidLoad()
{
super.viewDidLoad()
languge = defaults.objectForKey("language") as! String
fetchLog()
}
func fetchLog()
{
let fetchRequest = NSFetchRequest(entityName: "Tips")
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate=NSPredicate(format: "language=%#", languge)
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Tips]
{
tips = fetchResults
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int
{
return tips.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> TipsTableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cellt", forIndexPath: indexPath) as! TipsTableViewCell
cell.tipsTextView?.text = tips[indexPath.row].textShort
cell.tipsTextView.editable=false
cell.tipsTextView.userInteractionEnabled=false
cell.tipsTextView.textColor = UIColor(red: 0x7E/255, green: 0x7A/255, blue: 0x7F/255, alpha: 1.0)
cell.selectionStyle = UITableViewCellSelectionStyle.Default
return cell
}
func tableView(_tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let cell = tableView(_tableView, cellForRowAtIndexPath: indexPath)
return cell.getHeight()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if(segue.identifier == "showDetailx"){
var indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()!
var detailViewController:TipViewController = segue.destinationViewController as! TipViewController
detailViewController.tip = tips[indexPath.row]
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("showDetailx", sender: self)
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
if cell.respondsToSelector("setSeparatorInset:")
{
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:")
{
cell.preservesSuperviewLayoutMargins = false
}
if cell.respondsToSelector("setLayoutMargins:")
{
cell.layoutMargins = UIEdgeInsetsZero
}
}
}

You have one problem on your estimatedHeightForRowAtIndexPath. You call there cellForRowAtIndexPath, that's why you get another calls to this method. You can remove that code and do the following:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return self.heightForBasicCellAtIndexPath(indexPath)
}
func heightForBasicCellAtIndexPath( indexPath: NSIndexPath) -> CGFloat
{
var sizingCell: UITableViewCell? = nil;
var token: dispatch_once_t = 0
dispatch_once(&token) {
sizingCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as? TipsTableViewCell
}
return sizingCell!.frame.size.height;
}
This method instantiates a sizingCell using GCD to ensure it’s created only once.
Hope this helps

I delete heightForRowAtIndexPath and estimatedHeightForRowAtIndexPath and add to viewDidLoad() this:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0

Related

Getting the TableView Section Title from TableViewCell, swift

I have a TableView with two kind of Cells, both are filled with a CollectionView. In the TableViewController I let them them display with a simple if Statement.
My TableViewController:
import UIKit
import RealmSwift
import Alamofire
import SwiftyJSON
let myGroupLive = DispatchGroup()
let myGroupCommunity = DispatchGroup()
class HomeVTwoTableViewController: UITableViewController {
var headers = ["Live", "Channel1", "ChannelTwo", "Channel3", "Channel4", "Channel5", "Channel6"]
override func viewDidLoad() {
super.viewDidLoad()
DataController().fetchSomeDate(mode: "get")
DataController().fetchSomeOtherData(mode: "get")
}
//MARK: Custom Tableview Headers
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return headers[section]
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.black
let header = view as! UITableViewHeaderFooterView
if section == 0 {
header.textLabel?.textColor = UIColor.black
view.tintColor = UIColor.white
}
else {
view.tintColor = UIColor.groupTableViewBackground
}
}
//MARK: DataSource Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return headers.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
//Choosing the responsible PrototypCell for the Sections
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellBig", for: indexPath) as! HomeVTwoTableViewCell
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellSmall", for: indexPath) as! HomeVTwoTableViewCellSmall
return cell
}
}
//Set custom cell height, has to match the CollectionView height
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 225.0
}
else {
return 120.0
}
}
}
My TableViewCellSmall:
import UIKit
import RealmSwift
var communities: Results<Community>?
class HomeVTwoTableViewCellSmall: UITableViewCell{
#IBOutlet weak var collectionView: UICollectionView!
}
extension HomeVTwoTableViewCellSmall: UICollectionViewDataSource,UICollectionViewDelegate {
//MARK: Datasource Methods
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return (communities?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellSmall", for: indexPath) as? HomeVTwoCollectionViewCellSmall else
{
fatalError("Cell has wrong type")
}
//Here I want my Sorting Statement to make unique content per collection view
//normal approach if no section is asked
let url : String = (communities?[indexPath.row].pictureUri)!
let name :String = (communities?[indexPath.row].communityName)!
cell.titleLbl.text = name
cell.imageView.downloadedFrom(link :"somelink")
return cell
}
//MARK: Delegate Methods
override func layoutSubviews() {
myGroupCommunity.notify(queue: DispatchQueue.main, execute: {
let realm = try! Realm()
communities = realm.objects(Community.self)
self.collectionView.dataSource = self
self.collectionView.delegate = self
})
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
do something
}
}
My Problem is now, I want the "Channel Cells" to fill with customized and different data, in the CollectionView. That means I need some sort of key to get the right data in the right cell. My approach would be to take the SectionHeader Title, but for some reasons I cant access it from the TableViewCellSmall. So I have all the data in all the Cells and cant sort them without my Key.
Thanks in Advance.
from what I understand you need to fill the collectionview of each cell with different contents and for this needs to identify the cell?
If so, I used the method below that helped me, you can try.
If in doubt let me know so I can help, I hope I have helped :)
//TableViewCell Add
var didCollectionViewCellSelect: ((Int) -> Void)?
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//TabelView Add
class myClass: UITableViewController
{
var storedOffsets = [Int: CGFloat]()
override func viewDidLoad()
{
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
guard let tableViewCell = cell as? myTableViewCell else { return }
let secao = indexPath.section*1000 //Section
let linha = indexPath.row //Row
let posicao = secao+linha
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: posicao)
tableViewCell.collectionViewOffset = storedOffsets[posicao] ?? 0
}
override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
guard let tableViewCell = cell as? myTableViewCell else { return }
let secao = indexPath.section*1000 //Section
let linha = indexPath.row //Row
let posicao = secao+linha
storedOffsets[posicao] = tableViewCell.collectionViewOffset
}
}
//CollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
let posicao = collectionView.tag
let secao = Int(collectionView.tag/1000) //Section
let linha = posicao-(secao*1000) //Row
var qtd = 0
if secao == 0 && arrStation.count > 0
{
qtd = arrStation.count
}
return qtd
}

how to display 2 different prototype cells at different different sizes

UPDATE:
I went a different route. Heres what I would like to do. Design my app that lets me save core data and view it in another console in tableview. Once in the tableview console, I can also see a chart at the top of the console as well.
What I did:
I created a UIViewController, dragged over an imageview just to use that as an example. I also dragged in a tableview, cells...etc.
My Problem:
I can view the blank tableview cells and see the sample image. Once I save the core data and go back to try viewing the data, I get an error. I have the datasource and delegate implemented but, do I need to put that in my code.
class ViewMealsViewController: UIViewController, NSFetchedResultsControllerDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var menuButton: UIBarButtonItem!
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController<MealStats> = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
do {
try fetchedResultController.performFetch()
} catch _ {
}
if revealViewController() != nil {
revealViewController().rearViewRevealWidth = 325
menuButton.target = revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:- Retrieve Stats
func getFetchedResultController() -> NSFetchedResultsController<MealStats> {
fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func taskFetchRequest() -> NSFetchRequest<MealStats> {
let fetchRequest = NSFetchRequest<MealStats> (entityName: "MealStats")
let timeSortDescriptor = NSSortDescriptor(key: "mealtype",
ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
let milesSortDescriptor = NSSortDescriptor(key: "mealname",
ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
fetchRequest.sortDescriptors = [timeSortDescriptor, milesSortDescriptor]
return fetchRequest
}
// MARK: - TableView data source
func numberOfSections(in tableView: UITableView) -> Int {
let numberOfSections = fetchedResultController.sections?.count
return numberOfSections!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
return numberOfRowsInSection!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let mealstats = fetchedResultController.object(at: indexPath) as! MealStats
cell.textLabel?.text = mealstats.mealtype
cell.detailTextLabel!.text = mealstats.mealname
return cell
}
// MARK: - TableView Deleteƒ
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let managedObject:NSManagedObject = fetchedResultController.object(at: indexPath) as! NSManagedObject
managedObjectContext.delete(managedObject)
do {
try managedObjectContext.save()
} catch _ {
}
}
// MARK: - TableView Refresh
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.reloadData()
}
}
UIViewController with a sample image for an example
Error I get once I try to view saved core data in the tableview
Use UITableViewController
add two different cells to tableview on storyboard,
set two unique identifiers for them i.e
Cell No. 1 identifier : iden_1
Cell No. 2 identifier : iden_2
then in your class
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell
if(condition)
{
cell = tableView.dequeueReusableCell(withIdentifier: "iden_1", for: indexPath)
let stats = fetchedResultController.object(at: indexPath) as! Stats
cell.textLabel?.text = stats.type
cell.detailTextLabel!.text = stats.name
}
else{
cell = tableView.dequeueReusableCell(withIdentifier: "iden_2", for: indexPath)
let stats = fetchedResultController.object(at: indexPath) as! Stats
cell.textLabel?.text = stats.type
cell.detailTextLabel!.text = stats.name
}
return cell
}
and use this for identifying height for both cells.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(condition)
return 100
return 200
}

How to make it such that there are two seperate groups of cells in the same tableview?

How do I make it such that when names2 is not equals to names, it will add the missing strings from names into the table view but with a different text style?
import UIKit
class TableViewController: UITableViewController {
var names = [String]()
var identities = [String]()
var names2 = [String]()
override func viewDidLoad() {
names = ["First", "Second", "Third", "Fourth"]
identities = ["A", "B", "C", "D"]
names2 = ["First", "Second"]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
cell?.textLabel!.text = names[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = identities[indexPath.row]
let viewController = storyboard?.instantiateViewControllerWithIdentifier(vc)
self.navigationController?.pushViewController(viewController!, animated: true)
}
}
For images in collection view
import UIKit
class MedalViewController: UICollectionViewController {
var imagesArray = [String]()
var identities = [String]()
var identities2 = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imagesArray = ["1", "2", "3"]
identities = ["Shield", "Tie", "Star"]
identities2 = ["Shield", "Tie"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(named: imagesArray[indexPath.row])
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let vc = identities[indexPath.row]
let viewController = storyboard?.instantiateViewControllerWithIdentifier(vc)
self.navigationController?.pushViewController(viewController!, animated: true)
viewController?.title = self.identities[indexPath.row]
}
}
How do I make it such that the missing identifier in this case "Star" in which its image is "3" is greyed out in the collectionsView?
You can check that names2 is contains names array object inside cellForRowAtIndexPath and then change the text style you want.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
cell?.textLabel!.text = names[indexPath.row]
if (names2.contains(names[indexPath.row])) {
cell.textLabel.textColor = UIColor.blackColor() //Set other style that you want
}
else {
cell.textLabel.textColor = UIColor.redColor() //Set other style that you want
}
return cell!
}
Edit: I doesn't get properly about image but you could try some thing like this.
if (identities2.contains(identities[indexPath.row])) {
cell.imageView = UIImage(named: identities[indexPath.row])
}
else {
cell.imageView = UIImage(named: "DefaultGrayImage") //Set default image not in identities2
}

How to select a UITableview Cell automatically?

I'm working on a Quiz App. I am getting questions from API. I'm using tableview for the Options.
Now when the user selects the answer for the 1st question & presses Next comes to the previous question. Then the selected answer has to remain selected.
I researched a lot and found this:
Programmatically emulate the selection in UITableViewController in Swift
But I can't automatically select the user selected answer in my table view.
This is my Present UI
VC
func getOptions(){
OptionArray.removeAll(keepCapacity: false)
Alamofire.request(.GET, "http://www.wins.com/index.php/capp/get_chapter_answers/\(EID)/\(QuestionID[Qindex])")
.responseJSON { (_, _, data, _) in
println(data)
let json = JSON(data!)
let catCount = json.count
for index in 0...catCount-1 {
let disp = json[index]["DISPLAY_STATUS"].string
if disp == "Y"{
let op = json[index]["ANSWER"].string
self.OptionArray.append(op!)
let ans = json[index]["RIGHT_ANSWER"].string
self.AnswerArray.append(ans!)
}
}
self.OptionTable.reloadData()
println(self.OptionArray.count)
}
}
#IBAction func Previous(sender: AnyObject) {
Qindex--
ShowQuestion()
}
#IBAction func Next(sender: AnyObject) {
Qindex++
ShowQuestion()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.OptionArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.OptionTable.dequeueReusableCellWithIdentifier("Option") as! OptionCell
cell.Optionlabel?.text = self.OptionArray[indexPath.row]
cell.layer.masksToBounds = true;
cell.layer.cornerRadius = 6;
cell.layer.borderWidth = 2.0
cell.layer.borderColor = colorsArray[1].CGColor
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! OptionCell;
if currentCell.selected == true{
currentCell.layer.borderWidth = 4.0
currentCell.layer.borderColor = colorsArray[6].CGColor
println(currentCell.Optionlabel?.text)
}
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! OptionCell;
if currentCell.selected == false{
currentCell.layer.borderWidth = 2.0
currentCell.layer.borderColor = colorsArray[1].CGColor
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
UPDATE
I have over 20 Questions. So i have to save the Selected answer for Each Questions separately.
I can't select the answer using the indexpath position because the options will change it positions randomly when it is accessed for the second time.
You can do it this way :
When you press next, store the selected answer's index into a variable and when you come back to previous, check that index in willDisplayCell method and the set your cell selected.
Take a variable in your controller
var selectedAnsIndexPath:NSIndexPath?
your next button action will be something like
#IBAction func Next(sender: AnyObject) {
self.selectedAnsIndexPath = tableView.indexPathForSelectedRow()
Qindex++
ShowQuestion()
}
and then
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if(indexPath == self.selectedAnsIndexPath)
{
cell.setSelected(true, animated: false)
}
}
Try this, it may work for you!
UPDATE
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.OptionTable.dequeueReusableCellWithIdentifier("Option") as! OptionCell
cell.Optionlabel?.text = self.OptionArray[indexPath.row]
cell.QueID = QuestionID[Qindex]
cell.layer.masksToBounds = true;
cell.layer.cornerRadius = 6;
cell.layer.borderWidth = 2.0
cell.layer.borderColor = colorsArray[1].CGColor
if let val = examDic[cell.QueID]
{
if self.OptionArray[indexPath.row] == val
{
selectedAnsIndexPath = indexPath
cell.setSelected(true, animated: true)
cell.layer.borderWidth = 4.0
cell.layer.borderColor = colorsArray[6].CGColor
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if selectedAnsIndexPath != nil{
OptionTable.deselectRowAtIndexPath(selectedAnsIndexPath!, animated: false)
self.tableView(OptionTable, didDeselectRowAtIndexPath: selectedAnsIndexPath!)
println(selectedAnsIndexPath!.row)
}
let indexPath = OptionTable.indexPathForSelectedRow();
let currentCell = OptionTable.cellForRowAtIndexPath(indexPath!) as! OptionCell;
if currentCell.selected == true{
currentCell.layer.borderWidth = 4.0
currentCell.layer.borderColor = colorsArray[6].CGColor
var sqid = QuestionID[Qindex]
var sanswer = currentCell.Optionlabel!.text
examDic[sqid] = sanswer!
println(examDic)
}
}

re-populating a tableview with new array elements when a cell is clicked in swift

thanks for all the help so far. I need, when a cell in UITableView is clicked, to re-populate the view with an array read from another class - just can find a way to refresh the view. Code as follows:
Thanks in advance - the help so far has been great for this newbie.
import UIKit
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
let textCellIdentifier = "TextCell"
var catRet = XnYCategories.mainCats("main")
//var catRet = XnYCategories.subCats("Sport")
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return catRet.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = catRet[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
//let currentCell = tableView.cellForRowAtIndexPath(indexPath)
//var selectedText = currentCell!.textLabel?.text
//println(selectedText)
let catRet2 = XnYCategories.mainCats(catRet[row])
println(catRet2)
println(catRet[row])
//catRet = catRet2
}
}
Call reloadData() on your tableView as follow
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
//let currentCell = tableView.cellForRowAtIndexPath(indexPath)
//var selectedText = currentCell!.textLabel?.text
//println(selectedText)
let catRet2 = XnYCategories.mainCats(catRet[row])
println(catRet2)
println(catRet[row])
// *** New code added ***
// remove the comment
catRet = catRet2
// call reloadData()
tableView.reloadData()
// *** New code added ***
}
just do this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
catRet = XnYCategories.mainCats(catRet[row])
tableView.reloadData()
}

Resources