class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
var tableView:UITableView!
var city = ["gz","dl","sz","bj","hz"]
var city2 = ["gd","ln","gx","he","se"]
var city3 = ["a","b","c","d","e"]
let cellid = "reusecell"
let mycellid = "customer"
override func viewDidLoad()
{
super.viewDidLoad()
tableView = UITableView(frame: CGRect(x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height), style: UITableViewStyle.Grouped)
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if section == 0
{
return city.count
}else if section == 1
{
return city2.count
}
else
{ print("section3 count")
return city3.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
if indexPath.section == 0
{
var cell = tableView.dequeueReusableCellWithIdentifier(cellid)
if cell == nil
{
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellid)
}
cell?.textLabel?.text = "\(city[indexPath.row])"
cell?.detailTextLabel?.text = "beautiful place"
cell?.imageView?.image = UIImage(named: "test.png")
cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell?.selectionStyle = UITableViewCellSelectionStyle.Gray
tableView.beginUpdates()
return cell!
}
else if indexPath.section == 1
{
var cell = tableView.dequeueReusableCellWithIdentifier(cellid)
if cell == nil
{
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellid)
}
cell?.textLabel?.text = "\(city2[indexPath.row])"
cell?.detailTextLabel?.text = "beautiful place"
cell?.imageView?.image = UIImage(named: "test.png")
cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell?.selectionStyle = UITableViewCellSelectionStyle.Gray
tableView.beginUpdates()
return cell!
}
else
{
var mycell:MyCellTableViewCell? = tableView.dequeueReusableCellWithIdentifier(mycellid) as? MyCellTableViewCell
if mycell == nil
{
print("section3")
mycell = MyCellTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: mycellid)
}
print("section3 config")
mycell?.title?.text = "\(city3[indexPath.row])"
mycell?.detailTitle?.text = "beautiful place"
mycell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
mycell?.imageView?.frame = CGRect(x: 0, y: 0, width: 50, height: 100)
mycell?.imageView?.image = UIImage(named:"test.png")
mycell?.selectionStyle = UITableViewCellSelectionStyle.Gray
return mycell!
}
}
//Section的头部标题
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "城市选择器"
}
//Section的尾部标题
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return "选择相应的城市"
}
//有几个部分
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
//section尾部的高度
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 28
}
//section头部的高度
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 28
}
//section行的高度
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if indexPath.section == 0
{
return 60
}
else if indexPath.section == 1
{
return 60
}
else
{
return 100
}
}
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class MyCellTableViewCell: UITableViewCell {
var title:UILabel?
var detailTitle:UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
title = UILabel(frame: CGRect(x: 100, y: 5, width: 50, height: 40))
detailTitle = UILabel(frame: CGRect(x: 100, y: 50, width: 50, height: 40))
self.addSubview(title!)
self.addSubview(detailTitle!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Custom Cell, I want to let him in the third section shows, but when I pulled down the TableView, the third paragraph of section does not display the content. I don't know what's the problem.
enter image description hereenter image description here
I assume that there is something wrong the MyCellTableViewCell.
Maybe you can have a look at that or include it?
Are the print commands from part#3 printed in the console?
U need to dynamically change the height of the table using the following:
var noOfRows = city.count + city2.count + city3.count;
var currentHeight = self.tableView(tableView, heightForRowAtIndexPath: indexPath)
var finalHeight = noOfRows * Int(currentHeight);
You will need to place is the correct delegate function to make sure that when the table is rendered the height is changed.
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 have filter which is done in dropdown table view in an view controller. The dropdown table view contains three section namely section 1, section 2 and section 3. For section 1 and section 3 should single selection and section 2 should be multiple selection. When tapping section 1 it expands table view cell and when tapping on section 2 will expand and section 1 will close the expansion.
When selecting the option from each section should stored even user close and reopens the filter dropdown table view.
I have four questions:
When user tap on different section it should automatically close already open sections?
Table view should adjust height and its position based number cells in each sections?
how to do multiple and single selection for three sections?
selected should be stored even if dropdown table view is close and reopened.
Here is the code which tried so far all question which i have mentioned above:
extension HomeViewController : UITableViewDelegate, UITableViewDataSource, ExpandableHeaderViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
if locationListBool == true {
return 1
} else {
return sectionss.count
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if locationListBool == true {
return autocompleteplaceArray.count
} else {
return sectionss[section].category.count
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if locationListBool == true {
return 0
} else {
return 30
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if locationListBool == true {
return 30
} else {
if (sectionss[indexPath.section].expanded) {
return 30
} else {
return 0
}
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if locationListBool == true {
return 0
} else {
return 2
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if locationListBool == true {
return nil
} else {
let header = ExpandableHeaderView()
header.contentView.backgroundColor = UIColor.white
header.customInit(title: sectionss[section].genre, section: section, delegate: self)
return header
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if locationListBool == true {
let cell = tableView.dequeueReusableCell(withIdentifier: "placecell", for: indexPath) as! locationNameTableViewCell
guard autocompleteplaceArray.count > 0 else {
return cell
}
cell.locationName.text = autocompleteplaceArray[indexPath.row]
return cell
} else {
let cell = dropDownTbl.dequeueReusableCell(withIdentifier: "dropDownCell", for: indexPath) as! dropDownCell
cell.dropDownLbl.text = sectionss[indexPath.section].category[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
if locationListBool == true {
let lastRowIndex = tableView.numberOfRows(inSection: 0)
if indexPath.row == lastRowIndex - 1 {
tableView.allowsSelection = true
} else {
tableView.allowsSelection = true
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if locationListBool == true {
if let indexPath = tableView.indexPathForSelectedRow {
let currentCell = tableView.cellForRow(at: indexPath) as! UITableViewCell
searchText.text = (currentCell.textLabel?.text)
searchText.text = autocompleteplaceArray[indexPath.row]
placeIDString = autocompletePlaceIDArray[indexPath.row]
print("placeIDString::::\(String(describing: placeIDString))")
if placeIDString != nil {
getPlaceIDLatLong(placeIDs: placeIDString!)
print("get lat long \(getPlaceIDLatLong(placeIDs: placeIDString!))")
}
// PrefsManager.sharedinstance.lastlocation = searchText.text
locationText = searchText.text
print("locationText::::\(String(describing: locationText))")
}
self.locationTableList.isHidden = true
}
else {
}
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
switch indexPath.section {
case 0:
if let previousIndexPath = indexPathOfSelectedRowPaidBy {
dropDownTbl.deselectRow(at: previousIndexPath as IndexPath, animated: false)
dropDownTbl.cellForRow(at: previousIndexPath as IndexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
indexPathOfSelectedRowPaidBy = indexPath as NSIndexPath?
dropDownTbl.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
case 1:
dropDownTbl.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark
default:
break
}
return indexPath
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
switch indexPath.section {
case 0:
if let previousIndexPath = indexPathOfSelectedRowPaidBy {
dropDownTbl.deselectRow(at: previousIndexPath as IndexPath, animated: false)
dropDownTbl.cellForRow(at: previousIndexPath as IndexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
indexPathOfSelectedRowPaidBy = nil
case 1:
dropDownTbl.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
default:
break
}
}
func toogleSection(header: ExpandableHeaderView, section: Int) {
sectionss[section].expanded = !sectionss[section].expanded
dropDownTbl.beginUpdates()
if sectionss[0].expanded{
dropDownTbl.layer.frame = CGRect(x: 15, y: 152, width: 345, height: 300)
} else if sectionss[1].expanded {
dropDownTbl.layer.frame = CGRect(x: 15, y: 152, width: 345, height: 230)
} else if sectionss[2].expanded {
dropDownTbl.layer.frame = CGRect(x: 15, y: 152, width: 345, height: 330)
} else {
dropDownTbl.layer.frame = CGRect(x: 15, y: 152, width: 345, height: 90)
}
for i in 0 ..< sectionss[section].category.count {
dropDownTbl.reloadRows(at: [IndexPath(row: i, section: section)], with: .automatic)
}
dropDownTbl.endUpdates()
}
}
Expandable table view header::
import UIKit
protocol ExpandableHeaderViewDelegate {
func toogleSection(header: ExpandableHeaderView, section: Int)
}
class ExpandableHeaderView: UITableViewHeaderFooterView {
var delegate: ExpandableHeaderViewDelegate?
var section: Int!
var collapaseHandlerArray = [String]()
let button = UIButton()
let button2 = UIButton()
override init(reuseIdentifier: String?){
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectheaderAction)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func selectheaderAction(gestureRecognizer: UITapGestureRecognizer) {
let cell = gestureRecognizer.view as! ExpandableHeaderView
}
func customInit(title: String, section: Int, delegate: ExpandableHeaderViewDelegate) {
self.textLabel?.text = title
self.section = section
self.delegate = delegate
}
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel?.font = UIFont(name: "Nunito-Light", size: 12)
self.textLabel?.textColor = UIColor(red: 64.0/255, green: 75.0/255, blue: 105.0/255, alpha: 1.0)
self.contentView.backgroundColor = UIColor.white
}
}
Dropdown table view cell:
class dropDownCell: UITableViewCell {
#IBOutlet weak var dropDownLbl: UILabel!
#IBOutlet weak var dropDwnBtn: UIButton!
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
}
}
Here is the screen shots when selection done in cell and after reopen filter selections are removed or options selected are changed, sections are not closed already expanded sections. Excepted result:
There is no built-in support for allowing differing numbers of cells to be selected in different sections of a table view.
However, the UITableViewDelegate protocol includes the function tableView(_:willSelectRowAt:).
If you read the docs on that function, it says:
Return Value
An index-path object that confirms or alters the selected
row. Return an NSIndexPath object other than indexPath if you want
another cell to be selected. Return nil if you don't want the row
selected.
So you should be able to set your view controller up as the delegate of the table view, set the allowsMultipleSelection flag to true, and implement logic in the tableView(_:willSelectRowAt:) function that provides the selection rules you want.
Take a stab at writing such a function and if you have trouble, post your code, tell us how it fails to meet your needs, and we'll try to help you fix it.
In my App I implemented Expandable tableview. It's worked perfectly but now I want to change the first section was already expandable mode but I unable to do that.
Here I have implemented my own native code for creating expandable tableview not using any third party libraries.
Here I post my Full code for Expandable TableView:
#IBOutlet weak var tableViewSecond: UITableView!
var hidden = [true]
override func viewDidLoad() {
super.viewDidLoad()
tableViewSecond.delegate = self
tableViewSecond.dataSource = self
InspectionArray = [["inspection_name":"AVM Inspection"], ["inspection_name":"Simple Inspection"], ["inspection_name":"BVM Inspection"]]
InspectionSectionArray = [["inspection_Session":"Current Inspection"], ["inspection_Session":"Past Inspection"], ["inspection_Session":"Future Inspection"]]
}
func numberOfSections(in tableView: UITableView) -> Int {
for _ in 0..<InspectionSectionArray.count {
hidden.append(true)
}
return InspectionSectionArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hidden[section] {
return 0
} else {
return InspectionArray.count
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.orange
headerView.tag = section
let label = UILabel()
label.text = (InspectionSectionArray[section] as AnyObject).value(forKey: "inspection_Session") as? String
label.frame = CGRect(x: 45, y: 5, width: 150, height: 35)
label.font = UIFont.boldSystemFont(ofSize: 15)
headerView.addSubview(label)
label.tag = section
let tapForheaderView = UITapGestureRecognizer(target: self, action: #selector(SecondViewController.tapFunction))
headerView.isUserInteractionEnabled = true
headerView.addGestureRecognizer(tapForheaderView)
return headerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 2
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "SecondTableViewCell", for: indexPath) as? SecondTableViewCell
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "SecondTableViewCell") as? SecondTableViewCell;
}
cell!.dataLbl.text = (InspectionArray[indexPath.row] as AnyObject).value(forKey: "inspection_name") as? String
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print(indexPath.row)
print("\(indexPath.section)","\(indexPath.row)")
}
func tapFunction(sender:UITapGestureRecognizer) {
let section = sender.view!.tag
let indexPaths = (0..<InspectionArray.count).map { i in return IndexPath(item: i, section: section) }
hidden[section] = !hidden[section]
tableViewSecond.beginUpdates()
if hidden[section] {
tableViewSecond.deleteRows(at: indexPaths, with: .fade)
} else {
tableViewSecond.insertRows(at: indexPaths, with: .fade)
}
tableViewSecond.endUpdates()
}
I believe you only need to change this:
// declare hidden as this
var hidden: [Bool] = []
override func viewDidLoad() {
super.viewDidLoad()
InspectionArray = [["inspection_name":"AVM Inspection"], ["inspection_name":"Simple Inspection"], ["inspection_name":"BVM Inspection"]]
InspectionSectionArray = [["inspection_Session":"Current Inspection"], ["inspection_Session":"Past Inspection"], ["inspection_Session":"Future Inspection"]]
// initialize hidden array so that the first is false and the rest true
hidden = Array<Bool>(repeating: true, count: InspectionSectionArray.count)
hidden[0] = false
tableViewSecond.delegate = self
tableViewSecond.dataSource = self
}
// and change numberOfSections to this
func numberOfSections(in tableView: UITableView) -> Int {
return InspectionSectionArray.count
}
Just change this function
func tapFunction(sender: UITapGestureRecognizer?) {
var section = 0
if sender != nil {
section = sender!.view!.tag
}
let indexPaths = (0..<InspectionArray.count).map { i in return IndexPath(item: i, section: section) }
hidden[section] = !hidden[section]
tableViewSecond.beginUpdates()
if hidden[section] {
tableViewSecond.deleteRows(at: indexPaths, with: .fade)
} else {
tableViewSecond.insertRows(at: indexPaths, with: .fade)
}
tableViewSecond.endUpdates()
}
And call self.tapFunction(sender: nil) in viewdidLoad.
I am creating a table view programmatically using custom cell.However when I test using VoiceOver Im getting "empty list" and "content is empty" even though there is value in the cell.Any suggestions?
My tableview -
func createTable(_ choicesArray:[String]){
myTableView = UITableView(frame: CGRect(x: 10, y: self.verticalPostion, width: 340, height: 300))
self.choicesData = choicesArray
myTableView.estimatedRowHeight = 70
myTableView.rowHeight = UITableViewAutomaticDimension
myTableView.allowsMultipleSelection = true
myTableView.register(AnswerCell.self, forCellReuseIdentifier: "cell")
myTableView.dataSource = self
myTableView.delegate = self
myTableView.isAccessibilityElement = false
myTableView.shouldGroupAccessibilityChildren = true
// myTableView.reloadData()
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
//more code for cell selection
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return choicesData.count
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, tableView);
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AnswerCell
cell.choiceLabel.text = self.choicesData[indexPath.row]
return cell
}
Code for Custom Cell -
class AnswerCell: UITableViewCell {
var choiceLabel = UILabel()
func configure(_ description: String) {
choiceLabel.text = description
applyAccessibility()
}
final func applyAccessibility() {
isAccessibilityElement = true
accessibilityLabel = choiceLabel.text!
accessibilityHint = "Double tap to play."
choiceLabel.isAccessibilityElement = false;
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(choiceLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
choiceLabel.frame = CGRect(x: 20, y: 0, width: 70, height: 30)
}
}
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.
}
}