Austin
Austin

Reputation: 1

Update tableview with new elements in swift

So I have this chunk of code in numberOfRowsInSection to change how many is shown based on what sidebar option is pressed (A different tableView). When the user selects the index #1 they should only seen the amount of rows that are present in the fetch request. Nothing will update when I change the index and I am guessing that is because it is not being refreshed/updated. What code should I use to update this correctly and where should it be placed?

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    if sidebarindex == 3{
    return feeds.count
    } else if sidebarindex == 2{
    return feeds.count
    } else if sidebarindex == 1{

        let moc = SwiftCoreDataHelper.managedObjectContext()
        var favNames: [String] = []
        let fetchRequestM = NSFetchRequest(entityName:"Favorite")
        if let favs = moc.executeFetchRequest(fetchRequestM, error: nil) as? [Favorite] {
            favNames = favs.map { $0.favoriteTitle }}

        if favNames.count != 0{
            return favNames.count
        }else{
            return 1
        }

    } else{
    return feeds.count
    }



}

Upvotes: 0

Views: 324

Answers (2)

Deepak Tagadiya
Deepak Tagadiya

Reputation: 2247

swift 4

func reloadTableData(){

   self.tableMyList.reloadData()
}

Upvotes: 0

CodeIt
CodeIt

Reputation: 769

Note: Beginner at IOS and Swift, so please tell me if I'm wrong. But this is my attempt at answering your question:

The code used to refresh the data in a tableView would be:

tableView.reloadData()

Without seeing the code I can't say exactly where to place it, but an educated guess would be to place it in the function that gets activated when the side bar item is pressed. Example:

@IBAction func sideBarItem1Pressed(sender: UIButton) {
    // Set the index here
    tableView.reloadData()
}

If you update your post with your code I may be able to determine where it goes.

Upvotes: 1

Related Questions