How to create sections with dynamic in uitableview or UICollectionview iOS swift?
Problem:
I want to create tableview datasource and delegate methods that i can change the index any time also want to add or update the section indexes.
Because i'm using case 0,1,2,3..etc in my datasource and delegate methods.So i have to remember the index what that means.Also changing in all the methods.
How can i avoid that and easily modifiable section in my tableview or collectionView?
Solution:
Yes it's true that if we put that like above it's confusing while your section had 100's of indexes.
You can easily solve by using the below type.
First you have to define your struct like below for indexing.
enum MySection {
static let name = 0
static let email = 1
static let password = 2
static let cpassword = 3
static let gender = 4
static let dob = 5
static let height = 6
static let weight = 7
}
My tableview datasource will be like below
func numberOfSections(in tableView: UITableView) -> Int {
return 8
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case MySection.name:
return 1
case MySection.email:
return 1
case MySection.password:
return 2
case MySection.cpassword:
return 1
case MySection.gender:
return 1
case MySection.dob:
return 1
case MySection.height:
return 1
case MySection.weight:
return 2
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case MySection.name:
return 10
case MySection.email:
return 10
case MySection.password:
return 20
case MySection.cpassword:
return 10
case MySection.gender:
return 10
case MySection.dob:
return 10
case MySection.height:
return 10
case MySection.weight:
return 20
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case MySection.name:
let nameCell = tableView.dequeueReusableCell(withIdentifier: "nameCell") as! NameCell
return nameCell
case MySection.email:
let emailCell = tableView.dequeueReusableCell(withIdentifier: "emailCell") as! EmailCell
return emailCell
default:
let nameCell = tableView.dequeueReusableCell(withIdentifier: "nameCell") as! NameCell
return nameCell
}
}
If you are using like above if order was changing then you can just change the value in the enum only it will be working well..
Comments
Post a Comment