Index out of Range Error with Custom TableView - ios

I have two TableViews, both of which are Custom. One of those is a Custom TableView with a Header cell. The second one is a custom TableView without a header cell. What I am trying to do is when someone taps on the first tableView, the tapped item gets added to the second TableView. The problem is when I try to add the second item, the app crashes with an Index Out Of Range Fatal Error. This is in Swift 3.
Here is my Code:
import UIKit
struct TableData {
var section: String = ""
var data = Array<String>()
var dataS = Array<String>()
init(){}
}
var data = Array<TableData>()
var wordData = Array<TableData>()
class MyCustomCell: UITableViewCell {
#IBOutlet var label: UILabel!
#IBOutlet var labelS: UILabel!
}
class MyCustomWordCell: UITableViewCell {
#IBOutlet var wordLabel: UILabel!
#IBOutlet var wordLabelS: UILabel!
}
class MyCustomHeader: UITableViewCell {
#IBOutlet var header: UILabel!
}
class TypeViewController: BaseViewController , UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
#IBOutlet var wordTableView: UITableView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return data[section].data.count
}
if tableView == self.wordTableView {
return wordData.count
}
return 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "TypeCell", for: indexPath) as! MyCustomCell
cell.label.text = data[indexPath.section].data[indexPath.row]
cell.labelS.text = data[indexPath.section].dataS[indexPath.row]
return cell
}
if tableView == self.wordTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! MyCustomWordCell
if wordData.count != 0 {
if wordData.count > indexPath.row {
cell.wordLabel.text = wordData[indexPath.row].data[0]
cell.wordLabelS.text = wordData[indexPath.row].dataS[0]
}
}
return cell
}
return UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == self.tableView {
return 7
} else {
return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if tableView == self.tableView {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "Header") as! MyCustomHeader
headerCell.header.text = data[section].section
return headerCell
}
return UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Header")
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == self.tableView {
var element: TableData
element = TableData()
element.data.append(data[indexPath.section].data[indexPath.row]);
element.dataS.append(data[indexPath.section].dataS[indexPath.row]);
wordData.append(element)
wordTableView.reloadData()
if wordData.count == 3 {
performSegue(withIdentifier: "segueFind", sender: self)
}
}
if tableView == self.wordTableView {
wordData.remove(at: indexPath.row)
wordTableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
addItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addItems() {
var new_elements:TableData
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj1);
new_elements.data.append(obj2);
new_elements.data.append(obj3);
new_elements.data.append(obj4);
new_elements.data.append(obj5);
new_elements.data.append(obj6);
new_elements.data.append(obj7);
new_elements.dataS.append(objS1);
new_elements.dataS.append(objS2);
new_elements.dataS.append(objS3);
new_elements.dataS.append(objS4);
new_elements.dataS.append(objS5);
new_elements.dataS.append(objS6);
new_elements.dataS.append(objS7);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj11);
new_elements.data.append(obj12);
new_elements.data.append(obj13);
new_elements.data.append(obj14);
new_elements.data.append(obj15);
new_elements.data.append(obj16);
new_elements.data.append(obj17);
new_elements.dataS.append(objS11);
new_elements.dataS.append(objS12);
new_elements.dataS.append(objS13);
new_elements.dataS.append(objS14);
new_elements.dataS.append(objS15);
new_elements.dataS.append(objS16);
new_elements.dataS.append(objS17);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj21);
new_elements.data.append(obj22);
new_elements.data.append(obj23);
new_elements.data.append(obj24);
new_elements.data.append(obj25);
new_elements.data.append(obj26);
new_elements.data.append(obj27);
new_elements.dataS.append(objS21);
new_elements.dataS.append(objS22);
new_elements.dataS.append(objS23);
new_elements.dataS.append(objS24);
new_elements.dataS.append(objS25);
new_elements.dataS.append(objS26);
new_elements.dataS.append(objS27);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj31);
new_elements.data.append(obj32);
new_elements.data.append(obj33);
new_elements.data.append(obj34);
new_elements.data.append(obj35);
new_elements.data.append(obj36);
new_elements.data.append(obj37);
new_elements.dataS.append(objS31);
new_elements.dataS.append(objS32);
new_elements.dataS.append(objS33);
new_elements.dataS.append(objS34);
new_elements.dataS.append(objS35);
new_elements.dataS.append(objS36);
new_elements.dataS.append(objS37);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj41);
new_elements.data.append(obj42);
new_elements.data.append(obj43);
new_elements.data.append(obj44);
new_elements.data.append(obj45);
new_elements.data.append(obj46);
new_elements.data.append(obj47);
new_elements.dataS.append(objS41);
new_elements.dataS.append(objS42);
new_elements.dataS.append(objS43);
new_elements.dataS.append(objS44);
new_elements.dataS.append(objS45);
new_elements.dataS.append(objS46);
new_elements.dataS.append(objS47);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj51);
new_elements.data.append(obj52);
new_elements.data.append(obj53);
new_elements.data.append(obj54);
new_elements.data.append(obj55);
new_elements.data.append(obj56);
new_elements.data.append(obj57);
new_elements.dataS.append(objS51);
new_elements.dataS.append(objS52);
new_elements.dataS.append(objS53);
new_elements.dataS.append(objS54);
new_elements.dataS.append(objS55);
new_elements.dataS.append(objS56);
new_elements.dataS.append(objS57);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Name"
new_elements.data.append(obj61);
new_elements.data.append(obj62);
new_elements.data.append(obj63);
new_elements.data.append(obj64);
new_elements.data.append(obj65);
new_elements.data.append(obj66);
new_elements.data.append(obj67);
new_elements.dataS.append(objS61);
new_elements.dataS.append(objS62);
new_elements.dataS.append(objS63);
new_elements.dataS.append(objS64);
new_elements.dataS.append(objS65);
new_elements.dataS.append(objS66);
new_elements.dataS.append(objS67);
data.append(new_elements)
}
}
The line where the error is given is the following:
if wordData.count > indexPath.row {
cell.wordLabel.text = wordData[indexPath.section].data[indexPath.row] //This one
cell.wordLabelS.text = wordDataS[indexPath.section].dataS[indexPath.row]
}
Attached are some Photos of the MainStoryboard:
https://www.dropbox.com/sh/s5k50ubas8wewo8/AACTkAsPDtgbOk3EOrb0LeDJa?dl=0

You data structures aren't really helping you here, but your problem is in using indexPath.section in your cellForRow:at: function for the wordTableView.
This function should use wordData[indexPath.row].data[0]:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "TypeCell", for: indexPath) as! MyCustomCell
cell.label.text = data[indexPath.section].data[indexPath.row]
cell.labelS.text = dataS[indexPath.section].dataS[indexPath.row]
return cell
}
if tableView == self.wordTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! MyCustomWordCell
if wordData.count != 0 {
if wordData.count > indexPath.row {
cell.wordLabel.text = wordData[indexPath.row].data[0]
cell.wordLabelS.text = wordDataS[indexPath.row].dataS[0]
}
}
return cell
}
return UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
}
Also, your numberOfRowsInSection is incorrect. It should be:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return data[section].data.count
}
if tableView == self.wordTableView {
return wordData.count
}
return 0
}

Related

Filtering query for Realm

I have a function which prints all the objects in my realm table to a table view. I would like to be able to filter these objects by their "muscle" property.
Here's my DB helper functions:
func getMusclesCount()-> Int {
let storedExercise = realm.objects(StoredExercise.self)
return storedExercise.count
}
//MARK:- getAllMuscelsNames
func getAllMusclesNames()-> [String] {
var musclesName = [String]()
let storedExercise = realm.objects(StoredExercise.self)
for exercise in storedExercise {
print("Muscle = \(exercise.muscle)")
musclesName.append(exercise.name)
}
return musclesName
}
Here's my Table View Controller class :
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DBHelper.shared.getAllMusclesNames().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
let muscle = DBHelper.shared.getAllMusclesNames()[indexPath.row]
cell.textLabel?.text = muscle
return cell
}
I've tried adding .Filter to 'let storedExercise' but I'm not sure how to set it up correctly. Any assitance would be greatly appreciated, thanks.
If your StoredExercise model looks like this
class StoredExercise: Object {
#objc dynamic var muscle = ""
}
then to get all of the exercises that are for the biceps, it's this
let bicepResults = realm.objects(StoredExercise.self).filter("muscle == 'biceps'")

How to add extra row to tableview with textfield text "Amount" in swift

This struct in HomeVC:
struct JsonData{
var name: String = ""
var categoryname: String = ""
var customerdetails: [cDetails] = [cDetails]()
init(name: String, categoryname: String, customerdetails: [cDetails]){
self.name = name
self.categoryname = categoryname
self.customerdetails = customerdetails
}
}
struct cDetails{
var dValue: String = ""
init(dValue: String) {
self.dValue = dValue
}
}
In numberOfRowsInSection if categoryname is Mobile i need extra row in tableview and in cellForRowAtindexPath i need its text cell?.searchTextfield.text = "Amount"
like below how to do that?
if section == 0 {
if categoryname == "Mobile"{
//here i need extra row with cell?.searchTextfield.text = "Amount"
}
else
{
return selectedDetail?.customerdetails.count ?? 0
}
}
below is code for present view controller, please help me in the below code.
class NewSearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
var cell : DetailTableViewCell?
var selectedDetail: JsonData?
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return selectedDetail?.customerdetails.count ?? 0
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "textfieldCell", for: indexPath) as! DetailTableViewCell
cell?.searchTextfield.delegate = self
if let value = selectedDetail?.customerdetails[indexPath.row] {
cell?.searchTextfield.text = value.dValue
} else {
cell?.searchTextfield.text = "missing data"
}
} else if indexPath.section == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "buttonCell", for: indexPath) as! DetailTableViewCell
}
return cell!
}
}
Please help me in the code.
try this
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if categoryname == "Mobile"{
return selectedDetail?.customerdetails.count + 1 ?? 0
}
else
{
return selectedDetail?.customerdetails.count ?? 0
}
}
}
then
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "textfieldCell", for: indexPath) as! DetailTableViewCell
cell?.searchTextfield.delegate = self
//play with this validation
if selectedDetail?.customerdetails.count - 2 >= indexPath.row
{
if let value = selectedDetail?.customerdetails[indexPath.row] {
cell?.searchTextfield.text = value.dValue
} else {
cell?.searchTextfield.text = "missing data"
}
}
else
{
cell?.searchTextfield.text = "Amount"
}
} else if indexPath.section == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "buttonCell", for: indexPath) as! DetailTableViewCell
}
return cell!
}
Somehow i can't add a comment so i will respond with this answer.
For what i can see, you're returning 2 in func numberOfSections(in tableView: UITableView).
I think you need to find a way to program this dynamically. For example, if you store all the data you need in an array. you can simply return arrayName.count
So i think you need to write a function to store all the data you need in an array. and return this in your TableView.
I hope i understood your problem well, and this answer made sense.

How to show a parent view which is outside tableview and is scrollable?

I have a scenario where I need to show a parent view with shadow and corner radius containing a long list of reusable items. I used a tableView to display items. But I stuck at making my tableview expand as much as its contentSize. It works but not accurate. Any solutions?
Edit:
Desired result:
I used the following reference for self sizing tableview.
Self Sizing UITableView
I made a few modifications as below:
final class SelfSizedTableView: UITableView {
var maxHeight = CGFloat.greatestFiniteMagnitude
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
self.layoutIfNeeded()
}
override var intrinsicContentSize: CGSize {
let height = min(contentSize.height, maxHeight)
let size = CGSize(width: contentSize.width, height: height)
return size
}
}
I used a parent tableView with a cell having my containerView and embedding this self sized tableView.
class MyContainerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - IBOutlets
#IBOutlet weak var parentTableView: UITableView!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func estimateDataHeight() -> CGFloat {
let detailCellHeight: CGFloat = 32
let headingCellHeight: CGFloat = 43
let headings: CGFloat = headingCellHeight*2
let detailsHeight: CGFloat = detailCellHeight*4
let baseHeight = headings + detailsHeight
let membersHeight =
CGFloat(sectionsArray.count) * detailCellHeight
return baseHeight + membersHeight
}
}
// MARK: - UITableViewDataSource
extension MyContainerViewController {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id = String(describing: MyContainerTVCell.self)
guard let cell = tableView
.dequeueReusableCell(withIdentifier: id, for: indexPath)
as? MyContainerTVCell else {
return UITableViewCell()
}
cell.policyDetails = dataSource
// my cheat/trick doesn't work on large data.
DispatchQueue.main.asyncAfter(deadline: .now()+0.4) {
tableView.beginUpdates()
cell.tableView.layoutIfNeeded()
cell.tableView.reloadData() // the overridden one
tableView.endUpdates()
}
return cell
}
}
extension MyContainerViewController {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return estimateDataHeight()
}
}
My cell class which has the self size tableView and containerView:
class MyContainerTVCell: UITableViewCell, UITableViewDataSource, UITableViewDelegate {
// MARK: - IBOutlets
#IBOutlet weak var containerView: UIView!
#IBOutlet weak var shadowView: UIView!
#IBOutlet weak var tableView: SelfSizedTableView!
// MARK: - Properties
let titles = ["Email ID:", "Mobile Number:", "Address:", "ID: "] // first section data array
let moreData: [String] = [] // remaining reusable sections array
// no of subsequent sections for moreData array type
var numberOfSections: Int {
return 4
}
// MARK: -
var dataSource: MyDataSource!
// MARK: - Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
override func layoutSubviews() {
super.layoutSubviews()
}
// MARK: - Setup
func setupView() {
containerView.rounded(with: 10)
shadowView.layer.applyShadow()
tableView.dataSource = self
tableView.delegate = self
}
}
// MARK: - UITableViewDataSource
extension MyContainerTVCell {
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSections + 1
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
if section == 0 { return titles.count + 1 }
else if section == 1 { return moreData.count + 1 }
else { return moreData.count }
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let headerID = String(describing: MyHeaderTVCell.self)
let itemID = String(describing: MyItemTVCell.self)
switch indexPath.section {
case 0:
if indexPath.row == 0 {
guard let cell = tableView
.dequeueReusableCell(withIdentifier: headerID, for: indexPath)
as? MyHeaderTVCell else {
return UITableViewCell()
}
cell.titleLabel.text = dataSource.title
return cell
} else {
guard let cell = tableView
.dequeueReusableCell(withIdentifier: itemID, for: indexPath)
as? MyItemTVCell else {
return UITableViewCell()
}
let item = titles[indexPath.row-1]
cell.titleLabel.text = item
cell.separatorView.isHidden = true
let data: String
switch indexPath.row {
case 1:
data = dataSource.emailID
case 2:
data = dataSource.mobileNo
case 3:
data = dataSource.address
case 4:
data = dataSource.name
case 5:
data = dataSource.age
case 6:
data = dataSource.id
case 7:
data = dataSource.office
case 8:
data = dataSource.academic
default: data = String()
}
cell.detailLabel.text = data
return cell
}
case 1:
if indexPath.row == 0 {
guard let cell = tableView
.dequeueReusableCell(withIdentifier: headerID, for: indexPath)
as? MyHeaderTVCell else {
return UITableViewCell()
}
cell.titleLabel.text = "More Data"
return cell
} else {
guard let cell = tableView
.dequeueReusableCell(withIdentifier: itemID, for: indexPath)
as? MyItemTVCell else {
return UITableViewCell()
}
let sectionIndex = indexPath.section-1
guard sectionIndex <= numberOfSections-1,
let section = sectionsArray?[indexPath.section-1] else {
return UITableViewCell()
}
cell.titleLabel.text = moreData[indexPath.row-1]
cell.separatorView.isHidden = true
switch indexPath.row {
case 1:
cell.detailLabel.text = section.a
case 2:
cell.detailLabel.text = section.b
case 3:
cell.detailLabel.text = "\(section.c ?? 0)"
case 4:
cell.detailLabel.text = section.d
case 5:
cell.detailLabel.text = section.e
case 6:
cell.detailLabel.text = section.f
if indexPath.section < numberOfSections {
cell.separatorView.isHidden = false
}
default: break
}
return cell
}
default:
guard let cell = tableView
.dequeueReusableCell(withIdentifier: itemID, for: indexPath)
as? MyItemTVCell else {
return UITableViewCell()
}
let sectionIndex = indexPath.section-1
guard sectionIndex <= numberOfSections-1,
let section = sectionsArray?[indexPath.section-1] else {
return UITableViewCell()
}
cell.titleLabel.text = moreData[indexPath.row]
cell.separatorView.isHidden = true
switch indexPath.row {
case 0:
cell.detailLabel.text = section.a
case 1:
cell.detailLabel.text = section.b
case 2:
cell.detailLabel.text = "\(section.c ?? 0)"
case 3:
cell.detailLabel.text = section.d
case 4:
cell.detailLabel.text = section.e
case 5:
cell.detailLabel.text = section.f
if indexPath.section < numberOfSections {
cell.separatorView.isHidden = false
}
default: break
}
return cell
}
}
}
// MARK: - UITableViewDelegate
extension MyContainerTVCell {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 { return 43 }
if indexPath.section == 1 && indexPath.row == 0 { return 43 }
return 32
}
}
Why would you want to expand tableView as much as its content size to make it scrollable, when tableView is already scrollable?
However, if you have some other content, aside from table, on the screen and you want them to scroll together, then you need to embed all your content into UIScrollView.
Then, make a height constraint for you tableView in xib/storyboard with any value.
Then you might do something like this:
// in your view controller
private var heightObservation: NSKeyValueObservation?
// called once, for example, in viewDidLoad()
private func setupTableView() {
...
observation = tableView.constraintFrameHeightToContentSizeHeight()
}
extension UITableView {
func constraintFrameHeightToContentSizeHeight() -> NSKeyValueObservation {
return observe(\.contentSize, changeHandler: { (tableView, _) in
tableView.heightConstraint?.constant = tableView.contentSize.height
})
}
}
// find height constraint
extension UIView {
var heightConstraint: NSLayoutConstraint? {
return constraints.first(where: { $0.firstAttribute == .height })
}
}
Don't forget to uncheck "Scrolling Enabled" in xib/storyboard for that table view.

Swift 3.0 multiple selection with select all cell

I have added data in table view and I have manually added "select all" option to the list at first position, now when the user selects the first option which is 'select all' then the person manually option "Select all" is not selected. Select all, click then work all person or deselect working but signal selection all the person not working "Select all"
I have tried the code below but it's not working so can any one help me to solve this?
var unchecked:Bool = true
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
// set the text from the data model
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.lblStudentName.text = getStudentName[indexPath.row]
if UnAll == "unselect" {
if indexPath.row == 0 {
cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
}
if indexPath.row == Int(selectedNumber) {
cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
}
if indexPath.row == Int(unSelectNumber) {
//var j = "\(i)"
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
}
}else
{
if(unchecked){
cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
}
else{
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
}
}
return cell
}
var UnAll = ""
var selectedNumber = ""
var unSelectNumber = ""
var checkselect:Bool = true
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UnAll.removeAll()
selectedNumber.removeAll()
unSelectNumber.removeAll()
if(indexPath.row == 0){
btnCheckBoxClick(sender: UIButton())
}else
{
UnAll = "unselect"
btnCheckBoxClick(sender: UIButton())
if checkselect {
selectedNumber = "\(indexPath.row)"
checkselect = false
}else
{
unSelectNumber = "\(indexPath.row)"
checkselect = true
}
print("the selected index is : \(indexPath.row)")
}
}
#IBAction func btnCheckBoxClick(_ sender: Any) {
if(unchecked){
unchecked = false
}
else{
unchecked = true
}
ObjTableview.reloadData()
}
Create a struct for model data with a Bool property. You can modify this property by cell selection.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var allCharacters:[Character] = []
override func viewDidLoad() {
super.viewDidLoad()
allCharacters = [Character(name: "All"),Character(name: "Luke Skywalker"),Character(name: "Leia Organa"),Character(name: "Advik Shah"),Character(name: "Aarav Modi")]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allCharacters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil{
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = allCharacters[indexPath.row].name
if allCharacters[indexPath.row].isSelected
{
cell?.accessoryType = .checkmark
}
else
{
cell?.accessoryType = .none
}
cell?.selectionStyle = .none
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0
{
allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
for index in allCharacters.indices
{
allCharacters[index].isSelected = allCharacters[indexPath.row].isSelected
}
}
else
{
allCharacters[indexPath.row].isSelected = !allCharacters[indexPath.row].isSelected
if allCharacters.dropFirst().filter({ $0.isSelected }).count == allCharacters.dropFirst().count
{
allCharacters[0].isSelected = true
}
else
{
allCharacters[0].isSelected = false
}
}
tableView.reloadData()
}
}
struct Character
{
var name:String
// var otherDetails
var isSelected:Bool! = false
init(name:String) {
self.name = name
}
}
Creating Array of Struct objects from array of dictionary
let SubjectArray = json["students"] as! [[String:Any]]
allCharacters = SubjectArray.map({ Character(name: $0["studentName"] as! String) })
allCharacters.insert(Character(name:"All"), at: 0)
I like #Pranil's suggestion of using a separate section for the "All" row, so I have stolen that.
You can use an NSMutableIndexSet for tracking the selected rows. This is simpler than having to create a new struct or array of booleans or something. The only thing you do need to be aware of is if your tableview allows row reordering then the index set needs to be adjusted accordingly.
Here is my implementation. The "all" state is determined by the number of selected rows being equal to the number of rows in the data source array.
I have just used simple table view accessories for the checkmarks, but I am sure you can see how to adopt your image based approach in cellForRow(at:)
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableview: UITableView!
let names: [String]? = ["Luke Skywalker","Leia Organa","Advik Shah","Aarav Modi"]
var selectedRows = NSMutableIndexSet()
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 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let names = self.names else {
return 0
}
return 0 == section ? 1 : names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
var text: String
var accessory = UITableViewCellAccessoryType.none
if 0 == indexPath.section {
text = "All"
if self.selectedRows.count == self.names!.count {
accessory = .checkmark
}
} else {
text = names![indexPath.row]
if selectedRows.contains(indexPath.row) {
accessory = .checkmark
}
}
cell.textLabel!.text = text
cell.accessoryType = accessory
return cell
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0 {
if self.selectedRows.count == self.names!.count {
self.selectedRows = NSMutableIndexSet()
} else {
self.selectedRows = NSMutableIndexSet(indexesIn: NSRange(location: 0, length: self.names!.count))
}
tableView.reloadData()
} else {
self.selectedRows.contains(indexPath.row) ? self.selectedRows.remove(indexPath.row) : self.selectedRows.add(indexPath.row)
let rows = [IndexPath(row: 0, section: 0), indexPath]
tableView.reloadRows(at: rows, with: .none)
}
return nil
}
}
I think you are using only one section in the table view. I suggest you use two sections in the table view, so that first section will contain only one row (Select All) and the second section will contain other options. When you click on Select All, that is in the first row of the first section you can make all the rows in the second section as selected while reloading the table view.
// MARK: - struct for cell item
struct CellItem {
var name : String
var isSelected:Bool! = false
init(name: String) {
self.name = name
}
}
class ViewController: UITableViewController {
#IBOutlet var viewTable: UITableView!
// Declare a boolean varaible to toggle the checkbox in the first section of table view
var isSelectAllSelected : Bool = false
var cellData: [CellItem] = []
override func viewDidLoad() {
super.viewDidLoad()
cellData = [CellItem(name: "Luke Skywalker"),CellItem(name: "Leia Organa"),CellItem(name: "Advik Shah"),CellItem(name: "Aarav Modi")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else
{
return cellData.count
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
// MARK: - Table view delegates
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = TableCell()
cell.selectionStyle = .none
if indexPath.section == 0 {
cell.textLabel?.text = "Select All"
if isSelectAllSelected{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
else
{
cell.textLabel?.text = cellData[indexPath.row].name
if cellData[indexPath.row].isSelected{
cell.accessoryType = .checkmark
}
else{
cell.accessoryType = .none
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0
{
cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
isSelectAllSelected = cellData[indexPath.row].isSelected
for index in cellData.indices
{
cellData[index].isSelected = cellData[indexPath.row].isSelected
}
}
else
{
cellData[indexPath.row].isSelected = !cellData[indexPath.row].isSelected
if cellData.filter({ $0.isSelected }).count == cellData.count
{
isSelectAllSelected = true
}
else
{
isSelectAllSelected = false
}
}
viewTable.reloadData()
} }
Hello u can take cheboxbutton action method inside view controller with addtarget method and assign tag indexpath.row so u can easily get the indexpath. from below code u can get the idea.
class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var ObjTableview: UITableView!
var arrStudent = ["1","2","3","4","5"]
var arrSelectedStudent :[Int] = []
var selectAll:Bool = false
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.
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrStudent.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
// set the text from the data model
cell.selectionStyle = UITableViewCellSelectionStyle.none
// cell.lblStudentName.text = getStudentName[indexPath.row]
cell.lblStudentName.text = arrStudent[indexPath.row]
cell.btnCheckbox.tag = indexPath.row
cell.btnCheckbox.addTarget(self, action:#selector(btnCheckBoxClick(sender:)), for: .touchUpInside)
if selectAll {
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
}else{
if arrSelectedStudent.contains(indexPath.row){
cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
}else{
cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func btnCheckBoxClick(sender: UIButton) {
if sender.tag == 0{
selectAll = true
}else
{
selectAll = false
if let index = arrSelectedStudent.index(of: sender.tag) {
arrSelectedStudent.remove(at: index)
}else{
arrSelectedStudent.append(sender.tag)
}
}
ObjTableview.reloadData()
}}

Custom TableView and Header

I have a single Custom TableView with a Header cell. The problem is that I am only able to display one set of data and the TableView will not currently scroll (Maybe because of only one set of data being displayed.) This is in Swift 3.
Here is my Code:
ViewController:
struct TableData {
var section: String = ""
var data = Array<String>()
var dataS = Array<String>()
init(){}
}
var data = Array<TableData>()
var dataS = Array<TableData>()
class MyCustomCell: UITableViewCell {
#IBOutlet var label: UILabel!
#IBOutlet var labelS: UILabel!
}
class MyCustomHeader: UITableViewCell {
#IBOutlet var header: UILabel!
}
class TypeViewController: BaseViewController , UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
#IBOutlet var scrollView: UIScrollView!
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].data.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyCustomCell
cell.label.text = data[indexPath.section].data[indexPath.row]
cell.labelS.text = dataS[indexPath.section].data[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "Header") as! MyCustomHeader
headerCell.header.text = data[section].section
return headerCell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
var element: TableData
element = TableData()
element.data.append(data[indexPath.section].data[indexPath.row]);
wordData.append(element)
element = TableData()
element.data.append(dataS[indexPath.section].dataS[indexPath.row]);
wordDataS.append(element)
if wordData[indexPath.section].data.count == 3 {
performSegue(withIdentifier: "segueFind", sender: self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
addItems()
print(data)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addItems() {
var new_elements:TableData
new_elements = TableData()
new_elements.section = "Gevurah - Judgement"
new_elements.data.append(obj1);
new_elements.data.append(obj2);
new_elements.data.append(obj3);
new_elements.data.append(obj4);
new_elements.data.append(obj5);
new_elements.data.append(obj6);
new_elements.data.append(obj7);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Hod - Reverberation"
new_elements.data.append(obj11);
new_elements.data.append(obj12);
new_elements.data.append(obj13);
new_elements.data.append(obj14);
new_elements.data.append(obj15);
new_elements.data.append(obj16);
new_elements.data.append(obj17);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Tiferet - Beauty"
new_elements.data.append(obj21);
new_elements.data.append(obj22);
new_elements.data.append(obj23);
new_elements.data.append(obj24);
new_elements.data.append(obj25);
new_elements.data.append(obj26);
new_elements.data.append(obj27);
data.append(new_elements)
new_elements = TableData()
new_elements.section = "Gevurah - Judgement"
new_elements.dataS.append(objS1);
new_elements.dataS.append(objS2);
new_elements.dataS.append(objS3);
new_elements.dataS.append(objS4);
new_elements.dataS.append(objS5);
new_elements.dataS.append(objS6);
new_elements.dataS.append(objS7);
dataS.append(new_elements)
new_elements = TableData()
new_elements.section = "Hod - Reverberation"
new_elements.dataS.append(objS11);
new_elements.dataS.append(objS12);
new_elements.dataS.append(objS13);
new_elements.dataS.append(objS14);
new_elements.dataS.append(objS15);
new_elements.dataS.append(objS16);
new_elements.dataS.append(objS17);
dataS.append(new_elements)
new_elements = TableData()
new_elements.section = "Tiferet - Beauty"
new_elements.dataS.append(objS21);
new_elements.dataS.append(objS22);
new_elements.dataS.append(objS23);
new_elements.dataS.append(objS24);
new_elements.dataS.append(objS25);
new_elements.dataS.append(objS26);
new_elements.dataS.append(objS27);
dataS.append(new_elements)
}
Also, I am getting an index out of range error on this line:
element.data.append(dataS[indexPath.section].dataS[indexPath.row]);
Attached are some Photos of the MainStoryboard:
https://i.stack.imgur.com/Yvw7I.png
i.stack.imgur.com/nLWZJ.png
https://i.stack.imgur.com/ralOb.png
Put some code for number of section in your class it will definitely work.
public func numberOfSections(in tableView: UITableView) -> Int
{
return dummyArray.count
}

Resources