switch between cells when segmentedControl has changed - ios

i have a custom UITableViewCell which contains an segmentedControl. This segmentedControl is suppose to control the second cell. When the index in segmentedControl has changed it should switch to another custom cell. How can i do something like this? i've tried implementing a IBAction in the viewController, but then i cant connect it to the segmentedControl in the xib file. If i put that method in the segmentedViewCell then i cant change the cells subclass. How can i obtain this?
Here is a little illustration. segmentedControl and the bottom view is in different cells.
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageViewCell", forIndexPath: indexPath) as ImageViewCell
cell.itemImage.image = itemFile
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("UtilityViewCell", forIndexPath: indexPath) as UtilityViewCell
cell.titleLabel.text = itemTitle
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCellWithIdentifier("DescViewCell", forIndexPath: indexPath) as DescViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
return cell
}
return nil
}

Here is a step by step. In your project's storyboard, create a UITableViewController scene. Add UITableViewCells in it as indicated in the image below. Change your first cell's style to "custom" and add a UISegmentedControl with non-ambiguous auto layout constraints in it.
Before setting your code,
Make sure that your UITableViewController scene has its class set
to "TableViewController".
Make sure to select Prototype Cells and Grouped TableView Style for your UITableView in Attributes Inspector.
Make sure that your UISegmentedControl has a view tag set to 1 (see image).
Make sure that the cell that contains the UISegmentedControl has
its identifier set to "SegmentCell".
Make sure that the second cell has its identifier set to "CellZero".
Make sure that the third cell has its identifier set to "CellOne".
Make sure that the fourth cell has its identifier set to "CellTwo".
Finally, your UITableViewController class file will contain the following code:
import UIKit
class TableViewController: UITableViewController {
var segment = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func segmentAction(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
segment = 0
case 1:
segment = 1
case 2:
segment = 2
default:
break
}
tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("SegmentCell", forIndexPath: indexPath) as UITableViewCell
cell.selectionStyle = .None //if necessary
let segmentControl = cell.viewWithTag(1) as UISegmentedControl
segmentControl.selectedSegmentIndex = segment
segmentControl.addTarget(self, action: "segmentAction:", forControlEvents: .ValueChanged)
} else {
switch segment {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier("CellZero", forIndexPath: indexPath) as UITableViewCell
case 1:
cell = tableView.dequeueReusableCellWithIdentifier("CellOne", forIndexPath: indexPath) as UITableViewCell
case 2:
cell = tableView.dequeueReusableCellWithIdentifier("CellTwo", forIndexPath: indexPath) as UITableViewCell
default:
break
}
}
return cell
}
}

Ok, this might take an iteration until I better understand your need.
This from a demo project of some flash cards and I use a segmented control to decide to display all the historical games or just those of a certain type (addition, subtraction, etc.) I had to deal with the issue of where to put the segmented control. Inside the table or above the table. The problem with inside the table is in my case the view reloads after each change.
But I do use he segmented control to change both the header and the cell contents.
So I can post the code for all this, or I can create a short demo code for the segmented control within a table cell (not sure how that will play out).

override func numberOfSections(in intableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func segmentAction(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
segment = 0
case 1:
segment = 1
case 2:
segment = 2
default:
break
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "SegmentCell", for: indexPath as IndexPath) as UITableViewCell
// cell.selectionStyle = .none //if necessary
let segmentControl = cell.viewWithTag(1) as! UISegmentedControl
segmentControl.selectedSegmentIndex = segment
segmentControl.addTarget(self, action: #selector(JobReportTableViewController.segmentAction(_:)), for: .valueChanged)
} else {
switch segment {
case 0:
cell = tableView.dequeueReusableCell(withIdentifier: "CellZero", for: indexPath as IndexPath) as UITableViewCell!
case 1:
cell = tableView.dequeueReusableCell(withIdentifier: "CellOne", for: indexPath as IndexPath) as UITableViewCell!
case 2:
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)as UITableViewCell!
default:
break
}
}
return cell
}
}

Related

Only first two sender.tag is working for section header in table view

I have a table view inside which I am calling multiple nib as row under section
// MARK:- EXTENSIONS TABLE VIEWS
*
extension HomeController: UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 9
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerCell = tableView.dequeueReusableCell(withIdentifier: TableCellConstants.hHeaderCell) as! HomeHeaderCell
headerCell.viewAllBtn.tag = section
headerCell.viewAllBtn.addTarget(self, action: #selector(self.viewAll), for: .touchUpInside)
headerView.addSubview(headerCell)
return headerView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 4{
guard let cell = self.productTableView.dequeueReusableCell(withIdentifier: TableCellConstants.trendingProductCell, for: indexPath) as? TrendingCell else{
return UITableViewCell()
}
return cell
}
else if indexPath.section == 5{
guard let cell = self.productTableView.dequeueReusableCell(withIdentifier: TableCellConstants.featureCell, for: indexPath) as? FeatureBrandCell else{
return UITableViewCell()
}
return cell
}else if indexPath.section == 6{
guard let cell = self.productTableView.dequeueReusableCell(withIdentifier: TableCellConstants.spotlightCell, for: indexPath) as? StoplightTableCell else{
return UITableViewCell()
}
return cell
}
guard let cell = self.productTableView.dequeueReusableCell(withIdentifier: TableCellConstants.momentCell, for: indexPath) as? PriviewProductCell else{
return UITableViewCell()
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 4{
return 310
}
else if indexPath.section == 5{
return 200
}
else if indexPath.section == 6{
return 320
}
else{
return 210
}
}
}
this is button action
#objc func viewAll(sender: UIButton){
print(sender.tag)
}
when I click on view all Button only first two section is working that means output is only 0 and 1 tags, remaining section button action not even working, I even put breakpoint nothing is coming on it, not only this even horizontal scroll is not working on collection view that I have under table view which
is under scroll view
I'm am not sure to what you did wrong in your code, however I created a test project to try and sort your issue out and I believe I have managed to do so.
My best guess at where you went wrong was either something to do with the UIButton's connection being made from interface builder to code. Or to do with how you specified which cells should be at which row and in which section, inside of the cellForRowAt method (I'll look at your code in more detail and update this if I find why your code was not working).
Heres the code in its entirety which worked for me:
View Controller:
NOTE: I changed the if statement blocks to a switch statement as I
thought it would make it easier to read, also as I did not have the
xib files you were using for the cells I created my own basic header
cell, I then used the basic preset table view cell for the cells
contained within each section. If you have not worked with switch
statements before, then I recommend you check out the section on them
in the swift language guide book:
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID127
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
// MARK:: Life-Cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(HeaderTableViewCell.nib(), forCellReuseIdentifier: HeaderTableViewCell.id)
}
// MARK: Button Actions
#objc func viewAll(sender: UIButton){
print(sender.tag)
}
// MARK: Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 9
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerCell = tableView.dequeueReusableCell(withIdentifier: HeaderTableViewCell.id) as! HeaderTableViewCell
headerCell.viewAllBtn.tag = section
headerCell.viewAllBtn.addTarget(self, action: #selector(viewAll), for: .touchUpInside)
headerView.addSubview(headerCell)
return headerView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Section 4"
return cell
case 5:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Section 5"
return cell
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Section 6"
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Unknown Section (Default)"
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 4:
return 310
case 5:
return 200
case 6:
return 320
default:
return 210
}
}
}
HeaderTableViewCell Cell xib
HeaderTableViewCell Code
class HeaderTableViewCell: UITableViewCell {
#IBOutlet var headerTitleLabel: UILabel!
#IBOutlet var viewAllBtn: UIButton!
static let id = "HeaderTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "HeaderTableViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
NOTE: Please also be aware that it probably would be a better idea for you to of just used a custom UIView instead of a custom UITableViewCell for your table view headers.
As i said I had collection view as row inside table view and that table view inside scroll view, so at last I removed scroll view from main view and kept all UI under table view now it working fine
Swift compiler get confused when we have three scrolling view working together so better avoid this, it is not best approach
Thanks #demented07 for your efforts

CellForItemAt: index path not updating variable

I am working with a UITableView that has a cell with a UISwitch in it. I have four tableViewCells, each from this same prototype cell. However, when I toggle the switch, the only way that the variables in the TableView CellForItemAt: section is when I pull the tableView so that it goes out of the screen, and the Reusable Cells are Reloaded. How can I make these variables refresh when the switches are toggled?
Here is my code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "onOffCell", for: indexPath) as! SettingsCellTableViewCell
if indexPath.section == 0 {
cell.textLabel?.text = OLLItems![indexPath.row]._text
if indexPath.row == 0 {
GlobalData.AllGlobalData.OLLImageState = cell.state //GlobalData.AllGlobalData.OLLImageState is an struct in another file
print("OLLImageState \(GlobalData.AllGlobalData.OLLImageState)")
}
if indexPath.row == 1 {
GlobalData.AllGlobalData.OLLAlgState = cell.state
print("OLLAlgState \(GlobalData.AllGlobalData.OLLAlgState)")
}
}
if indexPath.section == 1 {
cell.textLabel?.text = PLLItems![indexPath.row]._text
if indexPath.row == 0 {
GlobalData.AllGlobalData.PLLImageState = cell.state
print("PLLImageState \(GlobalData.AllGlobalData.PLLImageState)")
}
if indexPath.row == 1 {
GlobalData.AllGlobalData.PLLAlgState = cell.state
print("PLLAlgState \(GlobalData.AllGlobalData.PLLAlgState)")
}
}
return cell
}
Try doing it this way
Below code works properly in my repo but I changed it a bit to justify your scenario
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "switchCell", for: indexPath) as! SwitchContainingTableViewCell
cell.mySwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
return cell
}
func switchChanged(_ mySwitch: UISwitch) {
guard let cell = mySwitch.superview?.superview as? SwitchContainingTableViewCell else {
return // or fatalError() or whatever
}
self.value = mySwitch.isOn //define var value in your controller or do it locally
let indexPath = itemTable.indexPath(for: cell)
if indexPath.section == 0 {
if indexPath.row == 0 {
GlobalData.AllGlobalData.OLLImageState = self.value
}
}
}
I have added a target of the switch and in the target I'm getting the changed state of the switch. The same can be done within the cellForItemAt: by using state = mySwitch.isOn
Hope this helps!

switching between different classes for UITableViewCell

I have two data sources, and two different classes for custom cells in my table.
I want by pressing one button to switch between sources and classes and update my UITableView accordingly.
Unfortunately It works only one time I switch from one set to another. It doesn't return back.
Hope my code will help to explain what I mean:
var displayMode : Int = 1
#objc func tappedButton(_ sender: UIButton?) {
if displayMode == 1 {
displayMode = 2
myTable.reloadData()
} else {
displayMode = 1
myTable.reloadData()
}
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if displayMode == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId,
forIndexPath: indexPath) as! Class1
cell.taskTitle.text = source1.text
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier(cellId,
forIndexPath: indexPath) as! Class2
cell.taskTitle.text = source2.text
return cell
}
}
Should I delete table cells before changing mode?
You use the same cellID in
let cell = tableView.dequeueReusableCellWithIdentifier(cellId,
forIndexPath: indexPath) as! Class1
and
let cell = tableView.dequeueReusableCellWithIdentifier(cellId,
forIndexPath: indexPath) as! Class2
Should be two different cells for 2 different classes (2 different IDS)
1) You need to create 2 separate classes for cells:
class FirstCellClass: UITableViewCell {}
class SecondCellClass: UITableViewCell {}
2) Then register the cells(or add cells in Storyboard):
tableView.register(FirstCellClass.self, forCellReuseIdentifier: String(describing: FirstCellClass.self))
tableView.register(SecondCellClass.self, forCellReuseIdentifier: String(describing: SecondCellClass.self))
3) Check display mode and return specific cell cellForRowAtIndexPath and items count in numberOfRowsInSection:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch displayMode {
case .first:
return firstDataSource.count
case .second:
return secondDataSource.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch displayMode {
case .first:
let cell = tableView.dequeueReusableCell(
withIdentifier: String(describing: FirstCellClass.self),
for: indexPath
) as! FirstCellClass
configureFirstCell(cell)
return cell
case .second:
let cell = tableView.dequeueReusableCell(
withIdentifier: String(describing: SecondCellClass.self),
for: indexPath
) as! SecondCellClass
configureSecondCell(cell)
return cell
}
}

UITableView background colour for bottom 5 rows

I do know how to input background colours for my row, but I don't really know how I can filter it by only the bottom 5 rows are "cell.backgroundColor = UIColor.red;" whereas the rest stays the same. Appreciate those who can help me this thanks!
P.S: Sorry as my swift is quite rusty.
UITableView Controller
import UIKit
import FirebaseDatabase
var postData2 = [String]()
var postData3 = [String]()
var tableDataArray = [tableData]()
class ResultsController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference() //set the firebase reference
// Retrieve the post and listen for changes
databaseHandle = ref?.child("Posts3").observe(.value, with: { (snapshot) in
postData2.removeAll()
postData3.removeAll()
tableDataArray.removeAll()
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = String(describing: snap.value!)
let rating = (value as NSString).integerValue
postData2.append(key)
postData3.append(value)
tableDataArray.append(tableData(boothName: key, boothRating: rating))
}
postData2.removeAll()
postData3.removeAll()
let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
for data in sortedTableData {
postData2.append(data.boothName)
let value = String(describing: data.boothRating)
postData3.append(value)
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postData2.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.font = UIFont.init(name: "Helvetica", size: 23)
cell.textLabel?.text = postData2[indexPath.row]
cell.detailTextLabel?.text = postData3[indexPath.row] + " ♥"
cell.detailTextLabel?.textColor = UIColor.red;
cell.detailTextLabel?.font = UIFont.init(name: "Helvetica", size: 23)
// cell.backgroundColor = UIColor.red;
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 80
}
}
class tableData {
var boothName: String
var boothRating: Int
init(boothName: String, boothRating: Int) {
self.boothName = boothName
self.boothRating = boothRating
}
}
A simple way is to have an conditional check to see if the indexPath.row value is within the last five.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red
}else{
cell.backgroundColor = UIColor.white /* Remaining cells */
}
return cell
}
Some of the other answers will work - but it is nicer to use cells that have a known configuration when they are dequeued by cellForRowAt, not deal with a bunch of possible starting conditions each time you dequeue a cell. To do this subclass the UITableViewCell and override prepareForReuse(). This function will be called just before a cell is returned by dequeueReusableCell. Then cells can be set to a known starting point before you configure them. If cells could be received configured any possible way in cellForRowAt, you soon wind up with a very long function with a lot of if/else conditions.
The condition
if indexPath.row >= postData2.count - 5 {
cell.backgroundColor = UIColor.red
}
can be used as it is, and prepareForReuse takes care of the cells not keeping any settings when they are recycled. Here's an example:
override func prepareForReuse() {
super.prepareForReuse()
backgroundColor = UIColor.white
}
With this one simple setting it's a wash whether you do the if/else approach or use subclassing to make the most of prepareForReuse. But as soon as you have more than one thing to set in a cell you will find it is far less complex to use this function and results in far fewer mistakes with the appearance of cells - consider what would happen if there were more than one possible color a cell could be, or there were multiple elements in the cell to be configured with multiple possible values...
You can add simple logic
if indexPath.row >=(postData2.count-5) {
cell.backgroundColor = UIColor.red
}else {
cell.backgroundColor = UIColor.white
}
Just check a condition for setting the red colour for last five rows.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red;
}else {
cell.backgroundColor = UIColor.white; //white colour for other rows
}
return cell
}
This method is recommended by the system, this method is more circumventing reuse in some cases (like when you modify the contents of a control in the cell surface)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
// Not the type of cell, if the queue will return nil, at this time requires create ⼀ cell
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
}
If it involves data processing, you can create a new NSMutableSet(), Used to store your operations (ordinary data is lost, stored in the didSelecetRow inside indexPath like) save anyway, a unique tag.
These are just solve the problem of multiplexing, to deal with discoloration, refer to the above solution.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if(indexPath.row >= postData2.count-5){
cell.backgroundColor = UIColor.red
}else{
cell.backgroundColor = UIColor.white /* Remaining cells */
}
return cell
}

How to add buttons and labels in first section of tableview and second section contains only labels

sections = [
Section.init(name: "SelectFromOptions", items: dealnameArray),
Section(name: "merchant Details", items:merchantdetailsArray),
Section(name: "How to use deals", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"]),
Section(name: "things to remember", items: ["exchange for cash not allowed"]),
Section(name: "Cancelation policy", items: ["Once bought cannot exchange"]),
Section(name: "what you get", items: ["Capacity buliding courses"])
]
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
//
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell? ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return sections[(indexPath as NSIndexPath).section].collapsed! ? 0 : 44.0
}
I want to add different labels and buttons in each section ,is it possible? ,By using bpove code all cells contains only labels,i want to add more labels and buttons in my firt section
This is simple. Just use two dynamic cells, one containing only labels and another containing buttons and label(or whatever as you required). And use one cell for 1st section and another for second section. That's it.
You need to create a custom cell. Create a new file called CustomCell.swift. Use the following snippet in this file
class CustomCell: UITableViewCell {
#IBOutlet weak var lbl: UILabel!
#IBOutlet weak var btn: UIButton!
}
Now go to storyboard and add a new prototype cell in your tableview. Select the newly created cell and set it's class to CustomCell in the identity inspector (third option - top right).
Set this cell's identifier to customCell in attributes inspector (fourth option - top right).
Add a button and a label to this newly created cell and hook up the outlets through connections inspector (last option - top right).
Go back to your code and in your cellForRowAtIndexPath, copy the following snippet
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
//Here you can access the button and the label as cell's property using
//cell.btn &
//cell.lbl
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
return cell
}
you can try that type code..
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowCount = 0
if section == 0 {
rowCount = Data1.count
}
if section == 1 {
rowCount = Data2.count
}
return rowCount
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexpath.section == 0
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let ip = indexPath
cell.textLabel?.text = Data1[ip.row] as String
return cell
}
else if indexpath.section == 1
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let ip = indexPath
cell.textLabel?.text = Data1[ip.row] as String
return cell
}
}
switch indexPath.section {
case 0:
//add buttons and labels here
//prase data
break
case 1:
//add only labels here
//parse data
break
default:
break
}
or you can do with if else as well
if indexpath.section = 0 {
// create button and label here
} else {
// create label here
}
You need to write this snippet in cellForRowAtIndexPath

Resources