UITableViewCell multiple select circle (Edit Control) coming randomly - ios

I created a ViewController with a UITableView as a subView.
import UIKit
class ViewController: UIViewController {
private var tableDataSource = [
"Lorem Ipsum is simply du.",
"It is a long established .",
"Lorem Ipsum come",
"All the Lorem .",
"The standard ch.",
"The generated.",
"Various versions."
]
private var isReorderingEnabled = false
private var isDeleteEnabled = false
#IBOutlet private var reorderCellsBarButton: UIBarButtonItem!
#IBOutlet private var selectCellsBarButton: UIBarButtonItem! {
didSet {
selectCellsBarButton.tag = ButtonTags.Select
}
}
#IBOutlet private var deleteCellsBarButton: UIBarButtonItem! {
didSet {
deleteCellsBarButton.tag = ButtonTags.Delete
}
}
#IBOutlet weak private var tableView: UITableView! {
didSet {
tableView.dataSource = self
tableView.delegate = self
tableView.allowsMultipleSelectionDuringEditing = false
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
}
}
}
extension ViewController {
private struct ButtonTags {
static let Delete = 2
static let Select = 1
}
private struct LocalizedStrings {
static let EnableReorderingText = "Reorder"
static let DisableReorderingText = "Done"
static let EnableSelectionText = "Select"
static let ConfirmDeletionText = "Delete"
static let DisableDeletionText = "Cancel"
}
}
extension ViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setDeleteBarButton(hidden: true, animated: false)
}
}
// IBActions
extension ViewController {
#IBAction private func reorderCells(_ sender: UIBarButtonItem) {
isReorderingEnabled = !tableView.isEditing
setSelectBarButton(hidden: isReorderingEnabled)
sender.title = isReorderingEnabled ? LocalizedStrings.DisableReorderingText : LocalizedStrings.EnableReorderingText
tableView.setEditing(isReorderingEnabled, animated: true)
tableView.reloadData()
}
#IBAction private func deleteCells(_ sender: UIBarButtonItem) {
isDeleteEnabled = !tableView.isEditing
setDeleteBarButton(hidden: !isDeleteEnabled)
selectCellsBarButton.title = isDeleteEnabled ? LocalizedStrings.DisableDeletionText : LocalizedStrings.EnableSelectionText
if sender.tag == ButtonTags.Delete {
deleteSelectedRows()
}
tableView.allowsMultipleSelectionDuringEditing = isDeleteEnabled
tableView.setEditing(isDeleteEnabled, animated: true)
tableView.reloadData()
}
}
// Custom Helper methods
extension ViewController {
private func setDeleteBarButton(hidden: Bool, animated: Bool = true) {
navigationItem.setRightBarButtonItems([(hidden ? reorderCellsBarButton : deleteCellsBarButton)], animated: animated)
}
private func setSelectBarButton(hidden: Bool, animated: Bool = true) {
self.navigationItem.setLeftBarButton((hidden ? nil : selectCellsBarButton), animated: animated)
}
private func deleteSelectedRows() {
guard let selectedRows = tableView.indexPathsForSelectedRows else { return }
let indexes = selectedRows.map { $0.row }
tableDataSource.remove(indexes: indexes)
tableView.deleteRows(at: selectedRows, with: .fade)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier, for: indexPath) as! CustomTableViewCell
customCell.setup(content: tableDataSource[indexPath.row], for : indexPath.row)
return customCell
}
}
// pragma - To Select/Edit/Move TableView Cells
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
tableDataSource.move(from: sourceIndexPath.row, to: destinationIndexPath.row)
let reloadingIndexPaths = IndexPath.createForNumbers(from: sourceIndexPath.row, to: destinationIndexPath.row)
DispatchQueue.main.async {
tableView.reloadRows(at: reloadingIndexPaths, with: .none)
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableDataSource.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .none)
}
}
}
// pragma - Settings for Edit/Move TableViewCell
extension ViewController {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
print("Edit- \(tableView.isEditing)")
return tableView.isEditing
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
print("Move- \(isReorderingEnabled)")
return isReorderingEnabled
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
print("Style- None")
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
print("indent- \(isDeleteEnabled)")
return isDeleteEnabled
}
}
In this, I have made three bar buttons,one for Reordering , and other two for Deletion and Cancellation.
So, for delete I have provided ability to select multiple rows.
But the problem is, when Reordering selected, the checkbox is still appearing(Not clickable though). And sometimes when Deletion selected, checkbox doesn't appear.
Cannot understand the absurd behaviour. Is this a bug of XCode ? Please help.
Added Content:
CustomTableViewCell class :
import UIKit
class CustomTableViewCell: UITableViewCell {
static let identifier = "customCellIdentifier"
#IBOutlet weak private var titleLabel: UILabel!
#IBOutlet weak private var backgroundImageView: UIImageView!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let selectionView = UIView()
selectionView.backgroundColor = UIColor.clear
selectedBackgroundView = selectionView
}
}
extension CustomTableViewCell {
func setup(content: String, for rowNumber: Int) {
titleLabel.text = content
let backgroundImageName = rowNumber % 2 == 0 ? ImageAssetNames.BlueMatte : ImageAssetNames.GreenThreads
backgroundView = UIImageView(image: UIImage(named: backgroundImageName))
}
}

Related

Call function from UITableViewCell from in ViewController Swift

I need to call function deleteButtonShowHide, which is in TeamsCell, from TeamsVC, when plusBtnTapped. I am trying to figure it out with protocol TeamsVCDelegate, but it doesn't work( It works vice versa for me. But I do not know how to implement something like cell.teamsCellDelegate = self
TeamsCell
import UIKit
protocol TeamsCellDelegate {
func deleteCell()
}
class TeamsCell: UITableViewCell {
#IBOutlet weak var teamNameLbl: UILabel!
#IBOutlet weak var deleteButton: UIButton!
var teamsCellDelegate: TeamsCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func updateCell(team: team) {
teamNameLbl.text = team.name
}
#IBAction func deleteButtonTapped(_ sender: Any) {
debugPrint("delet tapped")
//deleteButtonShowHide()
findAndDeleteTeam()
teamsCellDelegate?.deleteCell()
}
func findAndDeleteTeam() {
for i in 0...teams.count - 1 {
if teams[i].name == teamNameLbl.text {
teams.remove(at: i)
break
}
}
}
func deleteButtonShowHide(){
if teams.count < 3 {deleteButton.isHidden = true}
if teams.count > 2 {deleteButton.isHidden = false}
}
}
extension TeamsCell: TeamsVCDelegate {
func deleteButtonSH() {
debugPrint("XXX")
deleteButtonShowHide()
}
}
TeamsVC
import UIKit
protocol TeamsVCDelegate {
func deleteButtonSH()
}
class TeamsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var plusBtn: UIButton!
#IBOutlet weak var teamsTable: UITableView!
var teamsVCDelegate: TeamsVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
teamsTable.delegate = self
teamsTable.dataSource = self
teamsTable.rowHeight = 55
teamsTable.isScrollEnabled = false
teamsTable.backgroundColor = nil
teamsTable.separatorStyle = .none
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return teams.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
#IBAction func plusBtnTapped(_ sender: Any) {
plusBtnHide()
addTeam()
teamsTable.reloadData()
teamsVCDelegate?.deleteButtonSH()
print(teams)
}
func plusBtnShow() {
if teams.count < 5 {plusBtn.isHidden = false}
}
func plusBtnHide() {
if teams.count == 4 { plusBtn.isHidden = true}
}
}
extension TeamsVC: TeamsCellDelegate {
func deleteCell() {
self.teamsTable.reloadData()
self.plusBtnShow()
}
}
You could call deleteButtonShowHide function when you are loading/setting up a cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
cell.deleteButtonShowHide() // <-- HERE
cell.teamsCellDelegate = self
return cell
}
return UITableViewCell()
}
By the way, your cell should not contain such logic in the first place. It should depend on some data model object which then should be used to setup your cell correctly (show/hide UI elements, etc.).
You could simplify by setting the button show/hide when computing the number of row.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if teams.count < 5 {plusBtn.isHidden = false}
if teams.count == 4 { plusBtn.isHidden = true}
return teams.count
}
And set the delebutton visibility when creating the cell :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "TeamsCell") as? TeamsCell {
cell.updateCell(team: teams[indexPath.row])
// cell.teamsCellDelegate = self
cell.deleteButton.isHidden = (teams.count < 3)
return cell
}
return UITableViewCell()
}
So no need for delegate and cell does not have to know about the model (teams)

Expandable drop down with Multi select checkbox in Swift

check / uncheck the check box by tapping the cell in table view and how to know which cell has checked or unchecked inside Expandable drop down in Swift.
VBExpandVC
class VBExpandVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var myTableView: UITableView!
struct Notification:Codable {
let notification:[Headings]
}
struct Headings:Codable {
var name:String
var status:Int
}
var names = [Headings]()
var expandTableview:VBHeader = VBHeader()
var cell : VCExpandCell!
override func viewDidLoad() {
super.viewDidLoad()
getNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
expandTableview = Bundle.main.loadNibNamed("VBHeader", owner: self, options: nil)?[0] as! VBHeader
let layer = expandTableview.viewHeader.layer
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 0.4
expandTableview.lblDate.text = self.names[section].name
expandTableview.btnExpand.tag = section
expandTableview.btnExpand.addTarget(self, action: #selector(VBExpandVC.headerCellButtonTapped(_sender:)), for: UIControl.Event.touchUpInside)
let str:String = "\(self.names[section].status)"//arrStatus[section] as! String
if str == "0"
{
UIView.animate(withDuration: 2) { () -> Void in
self.expandTableview.imgArrow.image = UIImage(named :"switch")
}
}
else
{
UIView.animate(withDuration: 2) { () -> Void in
self.expandTableview.imgArrow.image = UIImage(named :"switch2")
}
}
return expandTableview
}
#objc func headerCellButtonTapped(_sender: UIButton)
{
print("header tapped at:")
print(_sender.tag)
var str:String = "\(self.names[_sender.tag].status)"
if str == "0"
{
self.names[_sender.tag].status = 1
}
else
{
self.names[_sender.tag].status = 0
}
// myTableView.reloadData()
myTableView.reloadSections([_sender.tag], with: .none)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
//Return header height as per your header hieght of xib
return 40
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
let str:Int = (names[section].status)
if str == 0
{
return 0
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? VCExpandCell
return cell;
}
func numberOfSections(in tableView: UITableView) -> Int
{
return self.names.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
//Return row height as per your cell in tableview
return 111
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected:\(indexPath.section)")
}
// getNotifications
func getNotifications(){
guard let url = URL(string: "https://www.json-generator.com/api/json/get/cgAhRPmZgy?indent=2") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
guard let data = data, error == nil, response != nil else {
return
}
do {
let headings = try JSONDecoder().decode(Notification.self, from: data)
self.names = headings.notification
DispatchQueue.main.async {
self.myTableView.reloadData()
}
} catch {
print(error)
}
}).resume()
}
// End
}
VCExpandCell
class VCExpandCell: UITableViewCell {
#IBOutlet weak var btnMobile: UIButton!
#IBOutlet weak var btnEmail: UIButton!
#IBOutlet weak var btnSms: 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
}
#IBAction func btnMobileApp(_ sender: UIButton) {
print("mobile app checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
#IBAction func btnSMS(_ sender: UIButton) {
print("sms checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
#IBAction func btnEmail(_ sender: UIButton) {
print("email checked")
print(sender.tag)
if sender.isSelected {
sender.isSelected = false
} else {
sender.isSelected = true
}
}
}
enter image description here
In the above code, I have two major problems.
selected check box positions are changing when expanded the section and expanded another section
Unable to find selected check boxes by tapping the cell in table view inside Expand drop down.
Have a look ont his given url:
https://github.com/AssistoLab/DropDown

DidSelectRowAt won't return desired item

I have dynamic table which displays a number of MKMapItems - these items are being displayed by cellForRowAt. But somehow if I click on the cell didSelectRow won't return the map item if I want to print it:
class SearchResultTableViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var visualEffectView: UIVisualEffectView!
private enum SegueID: String {
case showDetail
case showAll
}
private enum CellReuseID: String {
case resultCell
}
private var places: [MKMapItem]? {
didSet {
tableView.reloadData()
}
}
private var suggestionController: SuggestionsTableTableViewController!
var searchController: UISearchController!
private var localSearch: MKLocalSearch? {
willSet {
places = nil
localSearch?.cancel()
}
}
private var boundingRegion: MKCoordinateRegion?
override func awakeFromNib() {
super.awakeFromNib()
...
}
override func viewDidLoad() {
super.viewDidLoad()
...
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 10, *) {
visualEffectView.layer.cornerRadius = 9.0
visualEffectView.clipsToBounds = true
}
}
...
}
extension SearchResultTableViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseID.resultCell.rawValue, for: indexPath)
if let mapItem = places?[indexPath.row] {
cell.textLabel?.text = mapItem.name
cell.detailTextLabel?.text = mapItem.placemark.formattedAddress
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print(indexPath)
...
guard let mapItem = places?[indexPath.row] else { return }
print(mapItem.name)
...
if tableView == suggestionController.tableView, let suggestion = suggestionController.completerResults?[indexPath.row] {
searchController.isActive = false
searchController.searchBar.text = suggestion.title
search(for: suggestion)
}
}
}
guard let mapItem = places?[indexPath.row] else { return }
- are you sure this guard statement isn't returning?
also, I'm not seeing where you're setting the VC as the tableView delegate/datasource.

How to apply filter based on multiple selected rows in UITableView using swift 3

Hello all m having multisectioned tableview design like
want to apply filter based on the selected rows in which all the selection is in OR condition except the searchcriteria section(this section is mandatory),now what i want to achieve is want to save all the selection and filter the data when user clicks on Apply button.How to achieve this.Please help.
note:i dont want to use any database coz in future i have to post all the selected values using POST method.
Code :
ViewController.swift
import UIKit
class ViewController: UIViewController,ExpandableHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableview: UITableView!
var sections = [
Section(sectionname: "Year" ,
cellnames: ["2017-2018","2016-2017","2015-2016"],
expanded: false,
subtitle: "Please select a Year"),
Section(sectionname: "School",
cellnames: ["School A","School B","School C"],
expanded: false,
subtitle: "Please select a School"),
Section(sectionname: "SearchCriteria",
cellnames: ["No of Students","No of Student on RTE","No of Differently Abled Students","No of Student Opted For School Transport"],
expanded: false,
subtitle: "Please select your SearchCriteria"),
Section(sectionname: "Class",
cellnames: ["IX","X","XI","XII"],
expanded: false,
subtitle: "Please select a Class"),
Section(sectionname: "Section",
cellnames: ["A","B","C","D","E"],
expanded: false,
subtitle: "Please Select a Section")
]
var selectIndexPath : IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.allowsMultipleSelection = true
selectIndexPath = IndexPath(row: -1, section: -1)
let nib = UINib(nibName: "ExpandableHeaderView", bundle: nil)
tableview.register(nib, forHeaderFooterViewReuseIdentifier: "expandableHeaderView")
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].cellnames.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (sections[indexPath.section].expanded)
{
return 44
}
else
{
return 0
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 2
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerview = tableview.dequeueReusableHeaderFooterView(withIdentifier: "expandableHeaderView") as! ExpandableHeaderView
headerview.customInit(title: sections[section].sectionname, subtitle: sections[section].subtitle, section: section, delegate: self)
return headerview
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "labelcell")
cell?.textLabel?.text = sections[indexPath.section].cellnames[indexPath.row]
cell?.accessoryType = (indexPath == selectIndexPath) ? .checkmark : .none
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectIndexPath = indexPath
self.sections[indexPath.section].subtitle = (tableview.cellForRow(at: indexPath)?.textLabel?.text)!
sections[indexPath.section].expanded = !sections[indexPath.section].expanded
tableview.beginUpdates()
tableview.reloadSections([indexPath.section], with: .automatic)
tableview.endUpdates()
}
func toggleSection(header:ExpandableHeaderView,section : Int)
{
sections[section].expanded = !sections[section].expanded
tableview.beginUpdates()
for i in 0 ..< sections[section].cellnames.count {
tableview.reloadRows(at: [IndexPath(row: i, section: section)], with: .automatic)
}
tableview.endUpdates()
}
#IBAction func done_action(_ sender: Any) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ExpandableHeaderView.xib
ExpandableHeaderView.swift
import UIKit
protocol ExpandableHeaderViewDelegate {
func toggleSection(header:ExpandableHeaderView,section:Int)
}
class ExpandableHeaderView: UITableViewHeaderFooterView {
var delegate :ExpandableHeaderViewDelegate?
var section : Int!
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var SubTitleLabel: UILabel!
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectHeaderView)))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder : aDecoder )
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectHeaderView)))
}
func selectHeaderView(gesture:UITapGestureRecognizer)
{
let cell = gesture.view as! ExpandableHeaderView
delegate?.toggleSection(header: self, section: cell.section)
}
func customInit(title:String,subtitle : String,section:Int,delegate:ExpandableHeaderViewDelegate)
{
self.TitleLabel.text = title
self.SubTitleLabel.text = subtitle
self.section = section
self.delegate = delegate
}
override func layoutSubviews() {
super.layoutSubviews()
self.TitleLabel?.textColor = UIColor.white
self.SubTitleLabel?.textColor = UIColor.white
self.SubTitleLabel?.alpha = 0.7
self.contentView.backgroundColor = UIColor.darkGray
}
}
Section.swift
import Foundation
struct Section
{
var sectionname : String!
var cellnames : [String]!
var expanded : Bool!
var subtitle : String!
init(sectionname:String,cellnames : [String],expanded : Bool,subtitle : String)
{
self.sectionname = sectionname
self.cellnames = cellnames
self.expanded = expanded
self.subtitle = subtitle
}
}
Please Help.I googled a lot but cant find the soultion of my scenario.

UITableView only updating on scroll up, not down

I have a UITableView that updates when I scroll up, but it does not update when I scroll down. Furthermore, when it does update it occasionally seems to "skip" a cell and update the next one.
There are 6 total cells that should populate
I've created the UITableView in the storyboard, set my constraints for both the hashLabel and the creditLabel in storyboard
Here is the image of the initial TableView:
And upon scrolling up, when updated properly:
...and when scrolling up "misses" a cell:
and of course, the class:
class HashtagController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var model:ModelData!
var currentCell: UITableViewCell!
#IBOutlet var hashtagTableView: UITableView!
let basicCellIdentifier = "CustomCells"
override func viewDidLoad() {
super.viewDidLoad()
model = (self.tabBarController as CaptionTabBarController).model
hashtagTableView.delegate = self
hashtagTableView.dataSource = self
self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "CherrySwash-Regular", size: 25)!, NSForegroundColorAttributeName: UIColor(red:27.0/255, green: 145.0/255, blue: 114.0/255, alpha: 1.0)]
configureTableView()
hashtagTableView.reloadData()
}
func configureTableView() {
hashtagTableView.rowHeight = UITableViewAutomaticDimension
hashtagTableView.estimatedRowHeight = 160.0
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//deselectAllRows()
hashtagTableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
hashtagTableView.reloadData()
}
func deselectAllRows() {
if let selectedRows = hashtagTableView.indexPathsForSelectedRows() as? [NSIndexPath] {
for indexPath in selectedRows {
hashtagTableView.deselectRowAtIndexPath(indexPath, animated: false)
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.quoteItems.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return customCellAtIndexPath(indexPath)
}
func customCellAtIndexPath(indexPath:NSIndexPath) -> CustomCells {
var cell = hashtagTableView.dequeueReusableCellWithIdentifier(basicCellIdentifier) as CustomCells
setTitleForCell(cell, indexPath: indexPath)
setSubtitleForCell(cell, indexPath: indexPath)
return cell
}
func setTitleForCell(cell:CustomCells, indexPath:NSIndexPath) {
let item = Array(Array(model.quoteItems.values)[indexPath.row])[0] as? String
cell.hashLabel.text = item
}
func setSubtitleForCell(cell:CustomCells, indexPath:NSIndexPath) {
let item = Array(model.quoteItems.keys)[indexPath.row]
cell.creditLabel.text = item
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
/*currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
var currentLabel = currentCell.textLabel?.text
var currentAuthor = currentCell.detailTextLabel?.text
model.quote = currentLabel!
model.author = currentAuthor!*/
}
}
class CustomCells: UITableViewCell {
#IBOutlet var hashLabel: UILabel!
#IBOutlet var creditLabel: UILabel!
}
As it turns out, the issue had to do with my estimatedRowHeight. In this case the row height was too large and it was effecting the way the table cells were being constructed.
So in the end I changed hashtagTableView.estimatedRowHeight = 160.0 to hashtagTableView.estimatedRowHeight = 80.0 and everything worked just fine.

Resources