How to make an expandable and collapsable UITableView (parent and child cells) in swift? - ios

I wanted to have a UITableView which is able to expand and collapse while clicking on cells.
When I load the page, I want the Tableview to be expanded like this and function collapse and expand by clicking on the header(see the date).
Any help is appreciated.

Thanks everyone. I have solved the problem at last.This is the final sample code.
1) //Arrays for header and Child cells.
var topItems = [String]()
var subItems = [String]()
//Section index reference
var selectedIndexPathSection:Int = -1
2) Added Two custom cells. - one as header and other as Cell.
// AgendaListHeaderTableViewCell.swift
import UIKit
class AgendaListHeaderTableViewCell: UITableViewCell {
#IBOutlet weak var agendaDateLabel: UILabel!
#IBOutlet weak var expandCollapseImageView: UIImageView!
#IBOutlet weak var headerCellButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Child cell:
// AgendaListTableViewCell.swift
import UIKit
class AgendaListTableViewCell: UITableViewCell {
#IBOutlet weak var agendaListContainerView: UIView!
#IBOutlet weak var moduleListTitleLabel: UILabel!
#IBOutlet weak var moduleDueOnStatusLabel: UILabel!
#IBOutlet weak var moduleLocationLabel: UILabel!
#IBOutlet weak var moduleStatusLabel: UILabel!
#IBOutlet weak var moduleDownLoadStatusImageView: UIImageView!
#IBOutlet weak var moduleStatusLeftSideLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
agendaListContainerView.layer.cornerRadius = 3.0
moduleStatusLabel.layer.borderWidth = 0.5
moduleStatusLabel.layer.borderColor = UIColor.clearColor().CGColor
moduleStatusLabel.clipsToBounds = true
moduleStatusLabel.layer.cornerRadius = 5.0
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
3) On View Controller:
// AgendaListViewController.swift
import UIKit
class AgendaListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var agendaListTableView: UITableView!
var appUIColor:UIColor = UIColor.brownColor()
var topItems = [String]()
var subItems = [String]()
var selectedIndexPathSection:Int = -1
override func viewDidLoad() {
super.viewDidLoad()
topItems = ["26th April 2017","27th April 2017","28th April 2017","29th April 2017","30th April 2017"]
subItems = ["Monday","TuesDay","WednessDay"]
}
override func viewWillAppear(animated: Bool) {
self.title = "AGENDA VIEW"
self.automaticallyAdjustsScrollViewInsets = false
agendaListTableView.tableFooterView = UIView(frame: CGRectZero)
}
//tableview delegate methods
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 85;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return topItems.count
}
func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCellWithIdentifier("agendaTableViewHeaderCellD") as! AgendaListHeaderTableViewCell
headerCell.agendaDateLabel.text = topItems[section]as String
//a buttton is added on the top of all UI elements on the cell and its tag is being set as header's section.
headerCell.headerCellButton.tag = section+100
headerCell.headerCellButton.addTarget(self, action: "headerCellButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
//minimize and maximize image with animation.
if(selectedIndexPathSection == (headerCell.headerCellButton.tag-100))
{
UIView.animateWithDuration(0.3, delay: 1.0, usingSpringWithDamping: 5.0, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
headerCell.expandCollapseImageView.image = UIImage(named: "maximize")
}, completion: nil)
}
else{
UIView.animateWithDuration(0.3, delay: 1.0, usingSpringWithDamping: 5.0, initialSpringVelocity: 5.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
headerCell.expandCollapseImageView.image = UIImage(named: "minimize")
}, completion: nil)
}
return headerCell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if( selectedIndexPathSection == section){
return 0
}
else {
return self.subItems.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let childCell = tableView.dequeueReusableCellWithIdentifier("agendaTableViewCellID", forIndexPath: indexPath) as! AgendaListTableViewCell
childCell.moduleListTitleLabel.text = subItems[indexPath.row] as? String
childCell.moduleLocationLabel.text = subItems[indexPath.row] as? String
childCell.moduleDueOnStatusLabel.text = subItems[indexPath.row] as? String
return childCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
//button tapped on header cell
func headerCellButtonTapped(sender:UIButton)
{
if(selectedIndexPathSection == (sender.tag-100))
{
selectedIndexPathSection = -1
}
else {
print("button tag : \(sender.tag)")
selectedIndexPathSection = sender.tag - 100
}
//reload tablview
UIView.animateWithDuration(0.3, delay: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve , animations: {
self.agendaListTableView.reloadData()
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The sample can be downloaded # https://github.com/alvinreuben/Expand-ColllapseTableView

**Try to implement below**
import UIKit
class BankDepositsHistoryVC: UIViewController {
#IBOutlet weak var tableView: UITableView!
let NORMAL_HEIGHT:CGFloat = 90
let EXPANDABLE_HEIGHT:CGFloat = 200
var SECTION_OTHER_CARDS = 0
var expandableRow:Int = Int()
override func viewDidLoad() {
super.viewDidLoad()
self.expandableRow = self.historyData.count + 1 // initially there is no expanded cell
self.tableView.reloadData()
}
// MARK: - TableViewDelegate Setup
extension BankDepositsHistoryVC : UITableViewDelegate,UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.historyData.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
let value = indexPath.section
let row = indexPath.row
switch (value){
case SECTION_OTHER_CARDS:
switch (row){
case self.expandableRow:
return EXPANDABLE_HEIGHT
default:
return NORMAL_HEIGHT
}
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DepositsHistoryCell", forIndexPath: indexPath) as! DepositsHistoryCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
self.expandableRow = indexPath.row // provide row to be expanded
//self.tableView.reloadSections(NSIndexSet(index: indexPath.row), withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.reloadData()
}
}

with the help of below method you can do that
for objective-c
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
for swift
func tableView(_ tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
just change the height for a row when its get clicked and reload the section.
when you design any cell in storyboard don't put bottom constraint on the expandable part.just put top and height constraint.Hope this help :)

Related

UITableViewCell multiple select circle (Edit Control) coming randomly

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))
}
}

design UI of app using tablview in swift

I want UI of my app to be similar like as shown in below image.
Using tableview i'm able to get Payment,Delivery,Build Team options as shown in image but for Build Profile,Manage Menu.. how do i do it using tableview ?
If not tableview for these options then what other control i can try.
this type of UI you are looking for and you can easily get by creating different Cell classes
UI Output :
Required Code
Step 1 - Create different Xib of table cell
class viewWithArrow: UITableViewCell {
#IBOutlet weak var headerLabel: UILabel!
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
}
}
class viewWithShadow: UITableViewCell {
#IBOutlet weak var shadowView: UIView!{
didSet{
shadowView.addShadowToView(color: .black)
}
}
#IBOutlet weak var headerLabel: UILabel!
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
}
}
Adding Shadow Effect :
extension UIView {
func addShadowToView(color:UIColor)
{
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = 0.2
self.layer.masksToBounds = false
self.clipsToBounds = false
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 5
}
}
View controller
class ViewController: UIViewController
{
var dataArray : [String] = ["11","22","33","44","55","66"]
#IBOutlet weak var homeVcTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
homeVcTableView.register(UINib(nibName: "viewWithShadow", bundle: nil), forCellReuseIdentifier: "viewWithShadow")
homeVcTableView.register(UINib(nibName: "viewWithArrow", bundle: nil), forCellReuseIdentifier: "viewWithArrow")
}
override func viewWillAppear(_ animated: Bool) {
self.homeVcTableView.delegate = self
self.homeVcTableView.dataSource = self
}
}
extension ViewController : UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0,1:
let cell = self.homeVcTableView.dequeueReusableCell(withIdentifier: "viewWithShadow", for: indexPath) as! viewWithShadow
cell.headerLabel.text = dataArray[indexPath.row]
return cell
default:
let cell = self.homeVcTableView.dequeueReusableCell(withIdentifier: "viewWithArrow", for: indexPath) as! viewWithArrow
cell.headerLabel.text = dataArray[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.homeVcTableView.frame.size.height*0.1
}
}
Working code link - https://drive.google.com/open?id=18mSlWAU_e4XElox4H-oTpqg8clD_HKwu

tableview using array not working - xcode 7.3

I'm designing an app for my school and I am trying to make a simple directory using a tableview within a view controller. I began by trying to make objects, but then switched to a more simple array, still without any luck. I do not know if it is a problem with the code or with the storyboard. Here is the code for the viewcontroller:
import UIKit
class DirectoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var backButton2: UIButton!
#IBOutlet weak var directoryTableView: UITableView!
// #IBOutlet weak var nameLabel: NSLayoutConstraint!
// let searchController = UISearchController(searchResultsController: nil)
// var directoryObjects: NSMutableArray! = NSMutableArray()
var names = ["Teacher 1", "Teacher 2", "Teacher 3"]
override func viewDidLoad() {
super.viewDidLoad()
/*
self.directoryObjects.addObject("Teacher 1")
self.directoryObjects.addObject("Teacher 2")
self.directoryObjects.addObject("Teacher 3")
self.directoryTableView.reloadData()
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Mark - tableview
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let directoryCell = self.directoryTableView.dequeueReusableCellWithIdentifier("directoryCell", forIndexPath: indexPath) as! DirectoryTableViewCell
// directoryCell.directoryLabel.text = self.directoryObjects.objectAtIndex(indexPath.row) as? String
directoryCell.directoryLabel.text = names[indexPath.row]
return directoryCell
}
#IBAction func backButton2Tapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Here is the code for the DirectoryTableViewCell:
import UIKit
class DirectoryTableViewCell: UITableViewCell {
#IBOutlet weak var directoryLabel: UILabel!
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
}
/*
func directoryTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
}
*/
}
You have to set the delegates. The easiest way is in the code.
In viewDidLoad add:
directoryTableView.delegate = self
directoryTableView.dataSource = self
This will allow those tableView functions to get called.
I'd also recommend changing:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 3
}
to:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return names.count
}

dynamic tableview inside custom tableviewcell

I'm trying to create a tableview with custom cells that each one holds a tableview.
I want to show the inner tableview just when it have some data (most of the time it's empty). I've managed to display the cells but can't display their tableview if it's populated with data.
The problem also is that the cell height needs to be dynamic according to the amount of data to display.
The cell code:
class feedViewCell: UITableViewCell , UITableViewDataSource , UITableViewDelegate {
#IBOutlet var feedCellImage: UIImageView!
#IBOutlet var feedCellUserName: UILabel!
#IBOutlet var feedCellDate: UILabel!
#IBOutlet var feedCellComments: UILabel!
#IBOutlet var cardView: UIView!
#IBOutlet var repliesTableView: UITableView!
var repliesArray:[Reply] = []
#IBAction func addComment(sender: AnyObject) {
}
override func awakeFromNib() {
super.awakeFromNib()
var nib = UINib(nibName: "feedComment", bundle: nil)
repliesTableView.registerNib(nib, forCellReuseIdentifier: "commentCell")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
cardSetup()
}
func cardSetup() {
cardView.layer.masksToBounds = false
cardView.layer.cornerRadius = 5
cardView.layer.shadowOffset = CGSizeMake(-0.2, 0.2)
cardView.layer.shadowRadius = 1
cardView.layer.shadowOpacity = 0.2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repliesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = repliesTableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as CommentFeedCell
cell.commentCellUserName.text = repliesArray[indexPath.row].userName
return cell
}
}
And the Main controller code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var comment = comments[indexPath.row]
let cell: feedViewCell = tableView.dequeueReusableCellWithIdentifier("feedCell", forIndexPath: indexPath) as feedViewCell
cell.feedCellUserName.text = comment.userName
cell.feedCellImage.backgroundColor = UIColor.redColor()
cell.feedCellComments.text = "\(comment.replies.count) COMMENTS"
cell.repliesArray = comment.replies
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyy"
cell.feedCellDate.text = dateFormatter.stringFromDate(NSDate())
if cell.repliesArray.count > 0 {
cell.repliesTableView.rowHeight = UITableViewAutomaticDimension
}
cell.repliesTableView.reloadData()
return cell
}
How to show the inner tableview only in cells which have comments (and hiding the tableview in cells with 0 comments)?
Call super in layoutSubviews and let us know what happens.
override func layoutSubviews() {
super.layoutSubviews()
cardSetup()
}

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