Adding index at uitableview is not working in Swift 2.0 - ios

I am loading contacts in UITableView and I want to add index at the right end for user to navigate through contacts.
I am using the code:
var indexOfNames = [String]()
let indexNames = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
indexOfNames = indexNames.componentsSeparatedByString(" ")
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return indexOfNames
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
let temp = indexOfNames as NSArray
return temp.indexOfObject(title)
}
But it is not working. When I tap on the index, the table view comes to the top row. i.e. A. I have set the delegates for tableview. Maybe there is some issues with Swift 2.0?

Adding index to UITableView working for me may help you (for swift 2.0):
var arrIndexSection : NSMutableArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
//MARK:- TableView Datasource/DataDelegate Method
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return arrIndexSection.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return arrIndexSection.objectAtIndex(section) as? String
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.arrIndexSection as? [String]
}

Related

Show row in section with same name of row value

I have a Struct of products, taken from Firebase db, like this:
struct Product {
var name: String
var type: String
var ingredients: String
var price: Double
}
and i want to populate a tableview with section (product type) and relative rows.
So I created an array with all product type:
let array = product.compactMap{$0.type}
Then i have removed duplicates and i used final array for numberofSection and titleForHeaderInSections and it works.
But now i want to show in each section only products with same type of section name.
How can I work on this?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product.count
}
You can group your products in a dictionary by type
let dict = Dictionary(grouping: product, by: { $0.type})
and then access that using your array of types
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let type = typesArray[section]
guard let count = dict[type]?.count else {
return 0
}
return count
}
Another option would be to creating the dictionary directly with the array index as key so it can be used directly in the tableView:numberOfRowsInSection
Dictionary(grouping: product, by: { typesArray.firstIndex(of: prod.type)! })
You can add struct Category for easier data manipulation. Just make a category for all product types and filter de the products that you need. With an array of categories that contains an array of products you will have all the information you need: products, count, type etc...
struct Category {
var type: String
var products: [Product]
}
let allProducts = [Product]()
let categorySet: Set<String> = allProducts.map({ $0.type }).toSet()
let categorys: [Category] = categorySet.map { (type) -> T in
return Category(type: type, products: allProducts.filter({ $0.type == type}) )
}
func numberOfSections(in tableView: UITableView) -> Int {
return categorys.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categorys[section].products.count
}
func tableView( tableView : UITableView, titleForHeaderInSection section: Int)->String
{
return categorys[section].type
}
Use filter like this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return product.filter { $0.type == "myType" }.count
}

TableViewController numberOfRowsInSection section

I have a controller with buttons and a TableViewController with 10 arrays. Each button has an index, which pass to TableViewController.
In TableViewController code looks like this:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if buttonIndex == 0 {
return array0.count
}
else if buttonIndex == 1 {
return array1.count
}
else if buttonIndex == 2 {
return array2.count
}
else if buttonIndex == 3 {
return array3.count
}
else if buttonIndex == 4 {
return array4.count
}
else if buttonIndex == 5 {
return array5.count
}
else if buttonIndex == 6 {
return array6.count
}
else if buttonIndex == 7 {
return array6.count
}
else if buttonIndex == 8 {
return array6.count
}
return array0.count
}
I want to automatically define current index to do this:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return array(currentIndex).count
}
How to do it?
One way to achieve what you want is by creating a map, with index as key and array as value.
So your code should look something like this:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return indicesArray[index].count
}
You can make nested array where to store your arrays like:
var mainArray = [array0,array1,array2 ... ]
Then in
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainArray[section].count
}
You have to make the collection of your array in the array and you could be able to return as your requirement.
At class level:
var arrOfArrayData = []
Just like that:
let array0 = [""]
let array1 = [""]
let array2 = [""]
let array3 = [""]
let array4 = [""]
let array5 = [""]
let array6 = [""]
arrOfArrayData = [array0,array1,array1,array3,array4,array5,array6]
return arrOfArrayData[section].count //numberOfRowsInSection
Your list which contains 10 values as an array:
let listData = [["value11", "value12"], ["value21", "value22"], ["value31", "value32"] ...]
Inside UITableViewDataSource delegate method:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData[section].count
}

Swift - how to create correct sectionForSectionIndexTitle?

I have a section index that contains full alphabet - however, sections in my table contains only a few letters (e.g. C, F, N, U).
I would like to modify sectionForSectionIndexTitle to properly show right sections when sliding finger over section index. I'm still not sure how to do it using sections.append...
Thank you for help.
This is how my code looks like:
Section.swift
struct Section
{
var heading : String
var items : [String]
init(title: String, objects : [String]) {
heading = title
items = objects
}
}
ViewController.swift
func updateSections(index : Int) {
switch index {
case 0:
sections.append(Section(title: "C", objects: ["Czech Republic"]))
sections.append(Section(title: "F", objects: ["France"]))
sections.append(Section(title: "N", objects: ["Norway"]))
sections.append(Section(title: "U", objects: ["USA"]))
default: break
}
tableViewOutlet.reloadData()
}
let arrIndexSection = ["A","B","C","D", "E", "F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
if segmentedControlOutlet.selectedSegmentIndex == 0 {
return arrIndexSection
} else {
return [""]
}
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
let temp = arrIndexSection as NSArray
return temp.indexOfObject(title)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = sections[section]
return section.items.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].heading
}
try following code in your project :
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
var tempIndex:Int = 0
for str in arrIndexSection {
if str == title {
return tempIndex
}
tempIndex += 1
}
return 0
}

Group and sort Backendless data in UITableview with Swift

I'm looking to group and sort a list of users from backendless, similar to iPhone contacts. I want to add sectionIndexTitlesForTableView(_:), titleForHeaderInSection(_:), and sectionForSectionIndexTitle(_:). I haven't found a tutorial on how to do this, and I have been stuck for weeks.
So far, I'm able to retrieve users and populate the table view. I also implemented UISearchBarDelegate.
var users: [BackendlessUser] = []
var filteredUsers : [BackendlessUser] = []
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return users.count
} else {
return self.filteredUsers.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if tableView == self.tableView {
let user = users[indexPath.row]
cell.textLabel?.text = user.name
} else {
let filteredUser = filteredUsers[indexPath.row]
cell.textLabel?.text = filteredUser.name
}
return cell
}
You must have a dictionary of array (name 'data' for example)
data["A"] = ["Ananas", "Anaconda", "Apple"]
data["B"] = ["Banana", "Baby"]
...
data["Z"] = ["Zoro"]
begin:
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var headers: [String] = []
var data : [String: [String]] = [:] // Choose your type
override func viewDidLoad(){
// Do your stuff...
headers = letters.keys.sort()
// init your data var
data = ...
tableView.reloadData()
}
for header:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return headers.count
}
func sectionHeaderTitlesForTableView(tableView: UITableView) -> [String]?{
return headers
}
func tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
return headers[section];
}
cell
func tableView(tableView: UITableView, numberOfRowInSection section: Int) -> Int {
// Exemple
return data[section].count
}

TableView error: titleForHeaderInSection/Swift

I am working on a table view project I've seen in a tutorial, then I came across this piece of code that gives me the **error: Definition conflicts with previous value.**
The piece of code is:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int, titleForHeaderInSection section:Int) -> String? {
// Return the number of rows in the section.
return animalSelectionTitles[section]
}
I have tried to change the String? into String or Int, but String gives me the same error and Int gives me an error on the return line.
Here's my complete code:
import UIKit
class AnimalTableViewController: UITableViewController {
var animalsDict = [String: [String]] ()
var animalSelectionTitles = [String] ()
let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
func createAnimalDict() {
for animal in animals {
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
if var animalValues = animalsDict[animalKey] {
animalValues.append(animal)
animalsDict[animalKey] = animalValues
} else {
animalsDict[animalKey] = [animal]
}
}
animalSelectionTitles = [String] (animalsDict.keys)
animalSelectionTitles.sort({ $0 < $1})
animalSelectionTitles.sort( { (s1:String, s2:String) -> Bool in
return s1 < s2
})
}
override func viewDidLoad() {
super.viewDidLoad()
createAnimalDict()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return animalSelectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int, titleForHeaderInSection section:Int) -> String? {
// Return the number of rows in the section.
return animalSelectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = animals[indexPath.row]
// Convert the animal name to lower case and
// then replace all occurences of a space with an underscore
let imageFilename = animals[indexPath.row].lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "_", options: nil, range: nil)
cell.imageView?.image = UIImage(named: imageFilename)
return cell
}
Two things:
1)
You should change your line
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
Currently it substrings from the 2nd character, which means that for the input Black Swan then animalKey would be equal to lack Swan. Instead you should use the following line:
let animalKey = animal.substringToIndex(advance(animal.startIndex, 1))
2)
There is no method in the UITableViewDataSource Protocol which is called tableView:numberOfRowsInSection:titleForHeaderInSection. Instead you need to split it into the following two methods:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let title = animalSelectionTitles[section]
return animalsDict[title]!.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return animalSelectionTitles[section]
}
UPDATE 1:
In your tableView:cellForRowAtIndexPath, you should also update the retrieving of the animal name to reflect what is stored in the dictionary like so:
// Configure the cell...
let secTitle = animalSelectionTitles[indexPath.section]
let animalName = animalsDict[secTitle]![indexPath.row]
cell.textLabel?.text = animalName

Resources