I would like to add one picture and some texts under UITableViewCell. Here is the result that I want to achieve:
But I can only implement UITableViewCell with pure codes. Anyone know how to add a picture or some texts under or above the UITableViewCell? Any suggestions would be appreciated. Here is my current result:
Here are my codes:
import UIKit
class AboutViewController : UITableViewController {
private let about = ["About us"]
private let termsOfService = ["Terms of service"]
private let privacyPolicies = ["Privacy policies"]
private let openSourceLicense = ["Open Source Libraries"]
private let sections = ["about", "termsOfService", "privacyPolicies", "openSourceLicense"]
let myTableView: UITableView = {
let mt = UITableView()
return mt
}()
override func viewDidLoad() {
super.viewDidLoad()
// register cell name
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
// set DataSource
myTableView.dataSource = self
// set Delegate
myTableView.delegate = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.rowHeight
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
print("Value: \(about[indexPath.row])")
} else if indexPath.section == 1 {
print("Value: \(termsOfService[indexPath.row])")
} else if indexPath.section == 2 {
print("Value: \(privacyPolicies[indexPath.row])")
} else if indexPath.section == 3 {
print("Value: \(openSourceLicense[indexPath.row])")
}
}
// return the number of cells each section.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return about.count
} else if section == 1 {
return termsOfService.count
} else if section == 2 {
return privacyPolicies.count
} else if section == 3 {
return openSourceLicense.count
} else {
return 0
}
}
// return cells
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "MyCell")
if indexPath.section == 0 {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = "\(about[indexPath.row])"
} else if indexPath.section == 1 {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = "\(termsOfService[indexPath.row])"
} else if indexPath.section == 2 {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = "\(privacyPolicies[indexPath.row])"
} else if indexPath.section == 3 {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = "\(openSourceLicense[indexPath.row])"
}
return cell
}
}
Thanks #Larme for all the help. Add the following codes will be able to add a UIImage to the header (Which means to implement a TableHeaderView):
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let logoView = UIImageView()
if section == 0 {
logoView.contentMode = .scaleAspectFit
let logo: UIImage = #imageLiteral(resourceName: "IMG_0517")
logoView.image = logo
view.addSubview(logoView)
return logoView
} else {
return nil
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 200
} else {
return tableView.rowHeight
}
}
Here is the final result shows:
Final result picture
If you would like to add some texts under the UITableViewCell, you can add a footer to the final section.
Related
I have a simple UITableViewController and none of the rows are displaying. The table view header and section headers are all there. I have never encountered this. Thoughts?
import UIKit
class DashboardTableViewController: UITableViewController {
var countyName: String?
var sections = ["Quota Over/Short", "Qualified Renewals", "Membership Dues"]
override func viewDidLoad() {
super.viewDidLoad()
if countyName != nil {
self.title = "\(countyName!) County"
} else {
self.title = "County Info"
}
let headerView = DashboardCollectionView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 200))
tableView.tableHeaderView = headerView
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return 2
} else {
return 9
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell")
}
if #available(iOS 13.0, *) {
cell?.textLabel?.textColor = .label
} else {
cell?.textLabel?.textColor = .black
}
cell?.textLabel?.font = UIFont(name: "HelveticaNeue-Regular", size: 25)
cell?.textLabel?.numberOfLines = 2
if indexPath.section == 0 {
cell?.textLabel?.text = "-500"
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell?.textLabel?.text = "Previous Year: 1500"
} else {
cell?.textLabel?.text = "Current Year: 1000"
}
} else {
cell?.textLabel?.text = "Test Dues"
}
return cell!
}
}
You didn't answer the question about Prototype or Code-based cell class, and the code you've shown (in cellForRowAt) is not the right way to use table view cells.
Without seeing your custom cell setup, try it like this with a "default" cell:
class DashboardTableViewController: UITableViewController {
var countyName: String?
var sections = ["Quota Over/Short", "Qualified Renewals", "Membership Dues"]
override func viewDidLoad() {
super.viewDidLoad()
if countyName != nil {
self.title = "\(countyName!) County"
} else {
self.title = "County Info"
}
// I don't have your DashboardCollectionView class, so I'm creating
// as plain UIView with a blue background
//let headerView = DashboardCollectionView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 200))
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 200))
headerView.backgroundColor = .blue
tableView.tableHeaderView = headerView
// register a default UITableViewCell
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "defaultCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1 {
return 2
} else {
return 9
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
//override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return UITableView.automaticDimension
//}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// don't do it like this
//var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
//if cell == nil {
// cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell")
//}
// dequeue a registered cell
let cell = tableView.dequeueReusableCell(withIdentifier: "defaultCell", for: indexPath)
if #available(iOS 13.0, *) {
cell.textLabel?.textColor = .label
} else {
cell.textLabel?.textColor = .black
}
cell.textLabel?.font = UIFont(name: "HelveticaNeue-Regular", size: 25)
cell.textLabel?.numberOfLines = 2
if indexPath.section == 0 {
cell.textLabel?.text = "-500"
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell.textLabel?.text = "Previous Year: 1500"
} else {
cell.textLabel?.text = "Current Year: 1000"
}
} else {
cell.textLabel?.text = "Test Dues"
}
return cell
}
}
Result:
If that works (which it will), then try to use this code to figure out why your custom cell is not working.
From the image it looks like UITableView allocated space for your cells. I would recommend testing the cell by
NOT reuse cell just to see if you can get something to show up
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
Set background color to something
cell.backgroundColor = .red
If you see the cell show up then you know at least the tableview is giving you the correct # of cells
I'm trying to create a number of section based on user input.
I'm able to do that, but the next step is to create button at the end of the section.
However, we do not know what's the last section since it's up to the user request.
It looks like this:
Now, I have created another cell for the button like so:
Here's my code so far:
var numberOfSection: Int = 0 {
didSet {
tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
if numberOfSection == 0 {
return 2
}
else if numberOfSection <= numberOfSection {
return numberOfSection + 1
}
return numberOfSection + 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else if section <= numberOfSection + 1 {
for _ in 0...numberOfSection {
return testeSpec.count
}
}
else {
return 1
}
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableSection = indexPath.section
if tableSection == 0 {
let cells = tableView.dequeueReusableCell(withIdentifier: "serverNumbCell", for: indexPath) as! CellOutlet
let txtFieldServerNumber = cells.txtFieldServerNumb
cells.lblSectionNumb.text = "Number of section:"
txtFieldServerNumber?.addTarget(self, action: #selector(sectionTxtFieldDidChange), for: .editingChanged)
return cells
}
else if tableSection <= numberOfSection + 1 {
for _ in 0...numberOfSection {
let cells = tableView.dequeueReusableCell(withIdentifier: "serverSpecCell", for: indexPath) as! CellOutlet
let specWS = testSpec[indexPath.row]
cells.labels.text = specWS.spec
return cells
}
}
else {
let cells = tableView.dequeueReusableCell(withIdentifier: "buttonCell", for: indexPath) as! CellOutlet
cells.btnResult.setTitle("OK", for: .normal)
return cells
}
return CellOutlet()
}
I have another class hooked up with all the outles.
How can I create that another button in a section after all those unknown number of sections?
Thankyou in advance
In ViewController class
class ViewController: UIViewController {
var numberOfSections: Int = 0
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSections + 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
"section"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if numberOfSections > section {
return 2
} else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ServerSpecCell") as? ServerSpecCell else {return UITableViewCell()}
cell.titleLabel.text = "Number of section"
cell.numberOfSectionAction = { userInput in
self.numberOfSections = userInput
self.tableView.reloadData()
}
return cell
}
if numberOfSections > indexPath.section {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ServerSpecCell") as? ServerSpecCell else {return UITableViewCell()}
return cell
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCell") as? ButtonCell else {return UITableViewCell()}
return cell
}
}
class ButtonCell: UITableViewCell {
override class func awakeFromNib() {
super.awakeFromNib()
}
}
In UITableViewCell subclass
class ServerSpecCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var serverTextField: UITextField!
var numberOfSectionAction: ((Int)->Void)?
override func awakeFromNib() {
super.awakeFromNib()
serverTextField.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func textFieldDidChangeSelection(_ textField: UITextField) {
guard let sections = Int(textField.text ?? "0") else { return }
numberOfSectionAction?(sections+1)
}
}
I have set separator to none on these two below table views which works fine until I implement the heightForRowAtIndexPath method. Once I do that, a new separator appears, that doesn't extend all the way to the right like the default separator, and each one has a varying thickness. What's going on and how can I get rid of the new separators?
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == editsTableView {
return 44.0
} else if tableView == selectionTableViewLeft || tableView == selectionTableViewRight {
let h = selectionTableViewLeft.frame.size.height / CGFloat(leftOptions.count)
if h > 44.0 {
return h
} else {
return 44.0
}
} else {
return 44.0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == selectionTableViewLeft {
return leftOptions.count
} else if tableView == selectionTableViewRight {
return rightOptions.count
} else {
return edits.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == editsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "editCell")!
if indexPath.row == 0 {
cell.textLabel?.text = "Issued by \(String(describing: edits[indexPath.row].name))"
} else {
cell.textLabel?.text = "Edited by \(String(describing: edits[indexPath.row].name))"
}
cell.detailTextLabel?.text = GlobalFunctions.shared.formattedTimestamp(ts: edits[indexPath.row].timeStamp, includeDate: true, includeTime: true)
return cell
} else {
var currentOptions: [String] = []
if tableView == selectionTableViewLeft {
currentOptions = leftOptions
} else {
currentOptions = rightOptions
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
colorCell(text: currentOptions[indexPath.row], cell: cell)
cell.textLabel?.font = UIFont.systemFont(ofSize: 20.0)
cell.textLabel?.textAlignment = .center
if currentOptions[indexPath.row] == "(Blank)" {
cell.textLabel?.attributedText = GlobalFunctions.shared.italic(string: "(Blank)", size: 20.0, color: .lightGray)
} else {
cell.textLabel?.text = currentOptions[indexPath.row]
}
return cell
}
}
I want to select a row from different sections of the same table-view. I am getting output that many rows are selecting but I want exactly only one selected row from each section.
Here is My Arrays:
var filterFeedUnderAll = ["Complex","NotComplex","Easy"]
var filterFeedUnderAllStocks = ["AllStocks","Portfolio","Watchlist","Sector","Ticker"]
var filterFeedUnderByDate = ["ByDate","ByComments","ByLikes"]
The methods I have used:
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
var count:Int?
if section == 0
{
count = filterFeedUnderAll.count
}
else if section == 1
{
count = filterFeedUnderAllStocks.count
}
else if section == 2
{
count = filterFeedUnderByDate.count
}
return count!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.m_HomeFeedFilterBaseTableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! HomeFeedFIlterBaseTableViewCell
switch (indexPath.section)
{
case 0:
cell.m_TableItemsLabel.text = filterFeedUnderAll[indexPath.row]
case 1:
cell.m_TableItemsLabel.text = self.filterFeedUnderAllStocks[indexPath.row]
case 2:
cell.m_TableItemsLabel.text = filterFeedUnderByDate[indexPath.row]
default:
cell.m_TableItemsLabel.text = "Other"
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cell = m_HomeFeedFilterBaseTableView.cellForRowAtIndexPath(indexPath) as! HomeFeedFIlterBaseTableViewCell
for selectedIndexPath: NSIndexPath in tableView.indexPathsForSelectedRows!
{
if selectedIndexPath.section == indexPath.section
{
cell.m_TableItemsLabel.textColor = selectedTextColor
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
I want to select one row from each section. Help me to achieve this task.
first of all you need to enable multiple selection in your tableView and then this is the code that I used to do that, note that I use a Dictionary with format [String:NSIndexPath] named selectedRows where I store one indexPath by section I do this in addSelectedCellWithSection
UPDATED for last swift
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
var filterFeedUnderAll = ["Complex","NotComplex","Easy"]
var filterFeedUnderAllStocks = ["AllStocks","Portfolio","Watchlist","Sector","Ticker","bla bla bla1","bla bla bla2","bla bla bla3","bla bla bla1","bla bla bla2","bla bla bla3","bla bla bla1","bla bla bla2","bla bla bla3"]
var filterFeedUnderByDate = ["ByDate","ByComments","ByLikes"]
var selectedRows = [String:IndexPath]()
var alert : UIAlertController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int
{
return 3
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! mycustomHeader
let layer = CAShapeLayer()
let corners = UIRectCorner.topLeft.union(UIRectCorner.topRight)
layer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: headerCell.frame.width, height: headerCell.frame.height), byRoundingCorners: corners, cornerRadii:CGSize(width: 20.0, height: 20.0)).cgPath
headerCell.layer.mask = layer
return headerCell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
var count:Int?
if section == 0
{
count = filterFeedUnderAll.count
}
else if section == 1
{
count = filterFeedUnderAllStocks.count
}
else if section == 2
{
count = filterFeedUnderByDate.count
}
return count!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! testCell
switch (indexPath.section)
{
case 0:
cell.lblName.text = filterFeedUnderAll[indexPath.row]
case 1:
cell.lblName.text = self.filterFeedUnderAllStocks[indexPath.row]
case 2:
cell.lblName.text = filterFeedUnderByDate[indexPath.row]
default:
cell.lblName.text = "Other"
}
cell.lblName.textColor = UIColor.black
if(self.indexPathIsSelected(indexPath)) {
cell.lblName.textColor = UIColor.red
}
return cell
}
func addSelectedCellWithSection(_ indexPath:IndexPath) ->IndexPath?
{
let existingIndexPath = selectedRows["\(indexPath.section)"]
selectedRows["\(indexPath.section)"]=indexPath;
return existingIndexPath
}
func indexPathIsSelected(_ indexPath:IndexPath) ->Bool {
if let selectedIndexPathInSection = selectedRows["\(indexPath.section)"] {
if(selectedIndexPathInSection.row == indexPath.row) { return true }
}
return false
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = self.tableView.cellForRow(at: indexPath) as! testCell
let previusSelectedCellIndexPath = self.addSelectedCellWithSection(indexPath);
if(previusSelectedCellIndexPath != nil)
{
let previusSelectedCell = self.tableView.cellForRow(at: previusSelectedCellIndexPath!) as! testCell
previusSelectedCell.lblName.textColor = UIColor.black
cell.lblName.textColor = UIColor.red
tableView.deselectRow(at: previusSelectedCellIndexPath!, animated: true)
}
else
{
cell.lblName.textColor = UIColor.red
}
for selectedIndexPath: IndexPath in tableView.indexPathsForSelectedRows!
{
if selectedIndexPath.section == indexPath.section
{
cell.lblName.textColor = UIColor.red
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
}
Hope this helps you, for me works perfect
When we click on table view cell it will expand but if other cells are already expanded they will not collapse means we can see all cells expanded at a time..
i used below code for single cell expand but not getting how to do for multiple cell
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 2 && indexPath.row == selectedRowIndex && thereIsCellTapped {
switch indexPath.row{
case 0:
return 119
case 1:
return 93
case 2:
return 117
case 3:
return 135
case 4:
return 93
case 5:
return 230
default:
return 140
}
}
return 55
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! PatientDetailsTableViewCell
if indexPath.section == 2 {
self.tableView.cellForRowAtIndexPath(indexPath)?.backgroundColor = UIColor.whiteColor()
if self.selectedRowIndex != -1 {
self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: self.selectedRowIndex, inSection: 2))?.backgroundColor = UIColor.whiteColor()
}
if indexPath.section == 2 && selectedRowIndex != indexPath.row {
self.thereIsCellTapped = true
self.selectedRowIndex = indexPath.row
currentCell.lblRightArrow.text = "P"
print(selectedRowIndex)
}
else {
// there is no cell selected anymore
self.thereIsCellTapped = false
self.selectedRowIndex = -1
currentCell.lblRightArrow.text = "p"
}
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
I used that code for expanding single cell but how to do for multiple cell I am not getting
please help....thanks in advance
After too much work i got the solution for expanding multiple cell so i am sharing here to help others..
for expanding cell you have to store the indexPath in array when click on cell then use that array at tableview delegate method for height.My code is below..
var selectedIndexPath : NSIndexPath?
var indexPaths : Array<NSIndexPath> = []
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath
if !indexPaths.contains(selectedIndexPath!){
indexPaths += [selectedIndexPath!]
}
else {
let index = indexPaths.indexOf(selectedIndexPath!)
indexPaths.removeAtIndex(index!)
}
tableView.beginUpdates()
tableView.endUpdates()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPaths.count>0 {
if indexPaths.contains(indexPath){
return 200
}
else {
return 50
}
}
return 50
}
Create a new file named as TableViewController subclass of UITableViewController and also take a UITableViewController from storyboard and assign the class TableViewController from Identity Inspector of Xcode and also name the cell identifier as Cell. Then implement the class bellow:
class TableViewController: UITableViewController {
var groupArray = [String]()
var boolArray : [String]!
var dataDic = [String : [String]]()
override func viewDidLoad() {
super.viewDidLoad()
groupArray = ["A","B","C"]
boolArray = [String](count: groupArray.count, repeatedValue: "0")
let groupA = ["CELL ONE","CELL TWO","CELL THREE","CELL FOUR","CELL FIVE"]
let groupB = ["CELL ONE","CELL TWO","CELL THREE","CELL FOUR","CELL FIVE"]
let groupC = ["CELL ONE","CELL TWO","CELL THREE","CELL FOUR","CELL FIVE"]
dataDic["A"] = groupA
dataDic["B"] = groupB
dataDic["C"] = groupC
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return groupArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
let boolForSec = boolArray[section] as String
if (Int(boolForSec) != 0) {
var arr = dataDic[groupArray[section]]
return arr!.count
}else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let boolForSec = boolArray[indexPath.section] as String
if (Int(boolForSec) != 0) {
var arr : [String] = dataDic[groupArray[indexPath.section]]!
cell.textLabel?.text = arr[indexPath.row] as String
}else {
}
// cell.textLabel?.text = "row \(indexPath.row)"
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
headerView.backgroundColor = UIColor.blueColor()
headerView.tag = section
let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width-10, height: 30)) as UILabel
headerString.text = groupArray[section] as String
headerView .addSubview(headerString)
let headerTapped = UITapGestureRecognizer (target: self, action:"sectionHeaderTapped:")
headerView .addGestureRecognizer(headerTapped)
return headerView
}
func sectionHeaderTapped(tapped: UITapGestureRecognizer){
let section = tapped.view?.tag
let boolForSec = boolArray[section!] as String
if (Int(boolForSec) != 0) {
boolArray[section!] = "0"
}else {
boolArray[section!] = "1"
}
tableView.reloadSections(NSIndexSet(index: section!), withRowAnimation: UITableViewRowAnimation.Fade)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}