Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use numberOfSections or numberOfRowsInSection ? (Swift 3)

enter image description here

Why ? I don't know why the output gave me 3 sections only. I am very confused about numberOfSections and numberOfRowsInSection.

What I don't know:

Why the output returns 3 sections only?

What I know:

I saw a few post on StackOverFlow, they said Sections are like a group, and Rows are like the cells in the sections. But I still feel a little confused.

like image 491
Yu On Avatar asked Oct 29 '25 15:10

Yu On


2 Answers

Well, func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented and func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int is UITableViews Data Source method, numberOfSections is not required when you want only the same type of repeated list in your TableView, Like: suppose you want to show below in your tableview

1

2

3

4

..

in that case you will be required numberOfRowsInSection return 4 here your table will return 4 cells, if you not give numberOfSections this method it will be 1 by default and you code will work without having this method in your class.

But Suppose you need to show in your tableview that 1 2 3 4 A B C D It can be achieved by entering these data in an Array as string and print that in cellForAt.

But to make more it organige, what you can do here for better view to the user is to use section. Like

Number

1

2

3

4

Alphabet

A

B

C

D

Here You have to use numberOfSections and it should return 2, one for Number and second for Alphabet. and 1,2,3,4 and A,B,C,D are the rows under their section Number and Alphabet. I hope You got it, else comment below I'll try again to make you understand. Thanks

like image 152
Abhishek Mitra Avatar answered Oct 31 '25 06:10

Abhishek Mitra


Yes, it's a kind of grouping but don't mix it up with the grouped appearance of the table view.

Simple example: Look at the icon of the Contacts.app

enter image description here

The letters are the sections, the containing contacts are the rows in the section.

Your output reveals you have 1 section with 11 rows.

like image 42
vadian Avatar answered Oct 31 '25 06:10

vadian