Cosmic Mind - How to resize view when TabsController is implemented - ios

I am having a problem on inserting a title to this screen.
How can I resize this view?
Here's my code where the TabsController is implemented:
class DashboardViewController: TabsController {
let screenSize = UIScreen.main.bounds
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare() {
super.prepare()
tabBar.lineColor = UIColor.CustomColor.blue
tabBar.setTabItemsColor(UIColor.CustomColor.grey, for: .normal)
tabBar.setTabItemsColor(UIColor.CustomColor.blue, for: .selected)
tabBarAlignment = .top
tabBar.tabBarStyle = .auto
tabBar.dividerColor = nil
tabBar.lineHeight = 2.0
tabBar.lineAlignment = .bottom
tabBar.backgroundColor = .white
}
}
Here's my option one code (and the option two code is the same):
class TeamProjectViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
prepareTabItem()
setupTableView()
}
fileprivate func setupTableView() {
tableView.backgroundColor = .white
tableView.allowsSelection = false
tableView.separatorColor = UIColor.CustomColor.lightGrey
tableView.register(UINib(nibName: "ProjectTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProjectTableViewCell
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
}
extension TeamProjectViewController {
fileprivate func prepareTabItem() {
tabItem.title = "Option 1"
}
}
And here's what's happening to my tabs:
Thank you!

In your code you do not have anywhere where you are actually setting a view over the TabsController, where a title could exist. You would need to wrap the TabsController in order to accomplish this. One way, is use a ToolbarController:
let toolbarController = ToolbarController(rootViewController: myTabsController)
toolbarController.toolbar.title = "my title"
This is one way of going about your issue.

If you want just 20 pixels to move the tabs below status bar you can use StatusBarController with displayStyle = .partial. That's how I workaround.
let tabsController = TabsController(viewControllers: [
MyViewController1(),
MyViewController2()
])
let statusBarController = StatusBarController(rootViewController: tabsController)
statusBarController .displayStyle = .partial
// add statusBarController to hierarchy

Related

How to handle multiple buttons in a custom UITableViewCell?

I have a custom UITableViewCell which has 2 buttons (for incrementing and decrementing) and a count label in it. What I want to achieve is to update countLabel appropriately when subtractButton or addButton is tapped.
My custom cell class:
class ItemOptionCell: UITableViewCell {
private var count = 0
private var countLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 14)
label.numberOfLines = 0
label.text = "0"
label.adjustsFontSizeToFitWidth = true
return label
}()
private let subtractButton: UIButton = {
let subButton = UIButton(type: .system)
subButton.setTitle("-", for: .normal)
subButton.addTarget(self, action: #selector(decreaseItemCount), for: .touchUpInside)
return subButton
}()
private let addButton: UIButton = {
let addButton = UIButton(type: .system)
addButton.setTitle("+", for: .normal)
addButton.addTarget(self, action: #selector(increaseItemCount), for: .touchUpInside)
return addButton
}()
// contains subtract, add buttons and item count
private var operationsStackView = UIStackView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .white
configureOperationsStackView()
}
func set(itemOption: ItemOption) {
itemLabel.text = itemOption.title
}
private func configureOperationsStackView() {
addSubview(operationsStackView)
// code for autolayout
}
#objc private func decreaseItemCount() {
if count > 0 {
count -= 1
}
updateCountLabel()
}
#objc private func increaseItemCount() {
count += 1
updateCountLabel()
}
private func updateCountLabel() {
countLabel.text = String(count)
}
Part of ViewController for handling table view delegates:
extension ItemOptionsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "Header #1"
label.backgroundColor = .orange
return label
}
func numberOfSections(in tableView: UITableView) -> Int {
return options.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! ItemOptionCell
let option = options[indexPath.section][indexPath.row]
cell.set(itemOption: ItemOption(title: option))
cell.selectionStyle = .none
return cell
}
}
All the forums I looked up only describe how to handle single buttons.
P.s. I read about assigning tags to buttons but found out that it's not a recommended way as when row count changes managing tags becomes problematic. Therefore, if possible, recommend a way with delegates or closures.
Use delegate for this purpose
protocol ItemOptionCellDelegate: AnyObject {
func didDecreaseItemTapped(in cell: ItemOptionCell)
func didIncreaseItemCount(in cell: ItemOptionCell)
}
class ItemOptionCell: UITableViewCell {
weak var delagate: ItemOptionCellDelegate?
...
private func decreaseItemCount() {
delegate?.didDecreaseItemTapped(in: self)
}
private func increaseItemCount() {
delegate?.didIncreaseItemCount(in: self)
}
in your ViewController
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! ItemOptionCell
let option = options[indexPath.section][indexPath.row]
cell.set(itemOption: ItemOption(title: option))
cell.selectionStyle = .none
cell.delegate = self
cell.countLabel.text = //some value
return cell
}
extension ItemOptionsViewController: ItemOptionCellDelegate {
func didDecreaseItemTapped(in cell: ItemOptionCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let option = options[indexPath.section][indexPath.row]
//do some stuff with your data, then reload table and set need value for count label.
}
func didIncreaseItemCount(in cell: ItemOptionCell) { ... }
Also, DON'T update countLabel inside cell implementation, basically you have to set value count from your model, for example in ViewController in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell func (in case you use MVC approach)
Forget about tags.
Create gesture recognisers in your cellForRowAt and assign them to the buttons:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
//Create gesture
//Create two of these: one will be for the add button and one for the minus one. Attach to eachh gesture a different function.
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
//Add the two different gestures to both of the buttons
cell.myButton.addGestureRecognizer(tap)
...
}
//Create two of these: one to add and one to subtract
#objc func tapped(){
print("ok")
//Perform your action here
}
Plus, when it comes to adding the buttons in the tableViewCell custom class, call contentView.addSubview(myButton) instead of addSubview(myButton).
Oh and obviously, remove all the stuff in your custom class where you add targets to buttons and stuff like that, only create and add the objects to the cell as I said before.
Edit:
Set your buttons as follows:
//Do this for both buttons
private let subtractButton: UIButton = {
let subButton = UIButton(type: .system)
subButton.setTitle("-", for: .normal)
return subButton
}()

TableView Collapse, why it's sticking up like this?

I'm setting up a collapsable tableView, but something strange happens on the collapsable item. When you look at the video keep an eye on the "Where are you located" line.. (I'm using a .plist for the question and answer items)
Where do I go wrong, is it somewhere in my code? I don't want to let that line stick on the top :(
Here is the code I'm using but I can't find anything strange...
class FAQViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var questionsArray = [String]()
var answersDict = Dictionary<String, [String]>() // multiple answers for a question
var collapsedArray = [Bool]()
#IBOutlet weak var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
// Hide the navigation bar on the this view controller
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addTableStyles()
readQAFile()
tableView.delegate = self
tableView.dataSource = self
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
func addTableStyles(){
navigationController?.isNavigationBarHidden = false
self.tableView?.backgroundView = {
let view = UIView(frame: self.tableView.bounds)
return view
}()
tableView.estimatedRowHeight = 43.0;
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
}
func readQAFile(){
guard let url = Bundle.main.url(forResource: "QA", withExtension: "plist")
else { print("no QAFile found")
return
}
let QAFileData = try! Data(contentsOf: url)
let dict = try! PropertyListSerialization.propertyList(from: QAFileData, format: nil) as! Dictionary<String, Any>
// Read the questions and answers from the plist
questionsArray = dict["Questions"] as! [String]
answersDict = dict["Answers"] as! Dictionary<String, [String]>
// Initially collapse every question
for _ in 0..<questionsArray.count {
collapsedArray.append(false)
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return questionsArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if collapsedArray[section] {
let ansCount = answersDict[String(section)]!
return ansCount.count
}
return 0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Set it to any number
return 70
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if collapsedArray[indexPath.section] {
return UITableView.automaticDimension
}
return 2
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:40))
headerView.tag = section
let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width, height: 50)) as UILabel
headerString.text = "\(questionsArray[section])"
headerView .addSubview(headerString)
let headerTapped = UITapGestureRecognizer (target: self, action:#selector(sectionHeaderTapped(_:)))
headerView.addGestureRecognizer(headerTapped)
return headerView
}
#objc func sectionHeaderTapped(_ recognizer: UITapGestureRecognizer) {
let indexPath : IndexPath = IndexPath(row: 0, section:recognizer.view!.tag)
if (indexPath.row == 0) {
let collapsed = collapsedArray[indexPath.section]
collapsedArray[indexPath.section] = !collapsed
//reload specific section animated
let range = Range(NSRange(location: indexPath.section, length: 1))!
let sectionToReload = IndexSet(integersIn: range)
self.tableView.reloadSections(sectionToReload as IndexSet, with:UITableView.RowAnimation.fade)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cellIdentifier = "Cell"
let cell: UITableViewCell! = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.numberOfLines = 0
let manyCells : Bool = collapsedArray[indexPath.section]
if (manyCells) {
let content = answersDict[String(indexPath.section)]
cell.textLabel?.text = content![indexPath.row]
}
return cell
}
override var prefersStatusBarHidden: Bool {
return true
}
}
You need to change the style of the tableView to grouped, when you initialize it:
let tableView = UITableView(frame: someFrame, style: .grouped)
or from Storyboard:
After that you will have this issue, which I solved by setting a tableHeaderView to the tableView that has CGFloat.leastNormalMagnitude as its height:
override func viewDidLoad() {
super.viewDidLoad()
var frame = CGRect.zero
frame.size.height = .leastNormalMagnitude
tableView.tableHeaderView = UIView(frame: frame)
}
Just remove your headerView from view hierarchy here
#objc func sectionHeaderTapped(_ recognizer: UITapGestureRecognizer) {
headerView.removeFromSuperview()
...
}
By the way, yes creating a openable tableview menu with using plist is one of the methods but it could be more simple. In my opinion you should refactor your code.

DidSelectRow is not working

Pretty much what the title says: DidSelectRow is not getting called, and I did check that I didn't use Deselect. I also checked that delegate and DataSource are connected to the tableViewController and the Selection was Single Selection. However, the method is still not getting called.
Does an empty tableView might have any effect to it(reason it's empty is because the user starts to populate it. I'm using CoreData for it)?
EDIT
This is what the method looks like:
var effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
var effect: UIVisualEffect!
let defaults = UserDefaults.standard
var userMagazineTitle = [User]()
var dataString = String()
override func viewDidLoad() {
super.viewDidLoad()
addProgrammatically()
let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
do{
let users = try PresistanceService.context.fetch(fetchRequest)
self.userMagazineTitle = users
self.tableView.reloadData()
}catch{
ProgressHUD.showError("Nothing to see here")
}
}
/ MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userMagazineTitle.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyFeedTableViewCell
cell.myHeadline?.text = userMagazineTitle[indexPath.row].title
cell.indentationLevel = 3
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let manage = PresistanceService.persistentContainer.viewContext
let del = userMagazineTitle[indexPath.row]
if editingStyle == .delete {
// Delete the row from the data source
manage.delete(del)
do{
try manage.save()
}catch{
ProgressHUD.showError()
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do{
userMagazineTitle = try manage.fetch(fetchRequest) as! [User]
}catch{
ProgressHUD.showError()
}
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "showUser", sender: indexPath)
navigationController?.navigationBar.isHidden = false
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showUser" {
let DestViewController = segue.destination as! UINavigationController
let targetController = DestViewController.topViewController as! CompanyTableViewController
let indexPath = sender as! IndexPath
let user = userMagazineTitle[indexPath.row].title
let user2 = userMagazineTitle[indexPath.row].rssurl
targetController.customUserInit(articlesindex: indexPath.row, title: user!, rssUrl: user2!)
}
}
func addProgrammatically() {
effectView.frame = view.bounds
tableView.addSubview(effectView)
effectView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
effectView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
} else {
// Fallback on earlier versions
effectView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
}
effectView.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
effectView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
effect = effectView.effect
effectView.effect = nil
self.tableView.separatorStyle = .none
tableView.backgroundView = UIImageView(image: UIImage(named: "myMagazines.jpg"))
tableView.backgroundView?.contentMode = .scaleAspectFill
tableView.clipsToBounds = true
navigationController?.navigationBar.isHidden = false
UIApplication.shared.statusBarStyle = .lightContent
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
}
}
Another thing that might lead to the issue is not selected selection kind. I lost my two hours for fixing this.
Cross check cell selection , if it is selected for no selection change it to single selection.
To do this programatically :
Swift : tableView.allowsSelection = YES;
Objective C: [tableView allowsSelection : YES];
==============================
This might be helpful to someone!
You have added a UIVisualEffectView view on top of tableview, which is not passing the touch events to tableview.
Setting effectView.isUserInteractionEnabled = false, should make this view pass touch events to the views underneath.
There could be two issues for this problem:
The method signature of the TableView DidSelectRow could be wrong. The current signature is:
Swift:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
ObjectiveC: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
You are setting the Delegate of the TableView to nil somewhere in the code.

Two UITableView in single UIViewcontroller not working properly

I want to implement following functionality in app show pict
But i have following problem show another pict
my code as follow
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if str == "Loading"{
return 0
}else if tableView == tbl2{
return arrSub.count
}else{
return self.displayData.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
//Code for the load secind table
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
return cell
}else{
//Code for the load first table
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "add.png"), forState:(UIControlState.Normal))
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Selected))
cell.btnAdd.addTarget(self, action: "addData:", forControlEvents: .TouchUpInside)
cell.btnAdd.tag = indexPath.row
}
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
//function call when user click Plus button
func addData(sender: UIButton!) {
arrSub .addObject(self.displayData .objectAtIndex(sender.tag))
var button:UIButton = sender.viewWithTag(sender.tag) as! UIButton
button.selected=true
button.userInteractionEnabled = false
NSLog("%#", arrSub)
[tbl2 .reloadData()]
}
I would suggest you to move your tableView Datasource and Delegate to separate classes. This is not a good practise at all. You will certainly mess up with your code.
What you are doing make code complexity, you can add you own custom class for tableView and can maintain it it all delegate datasource methods.Add that tableview in current class and with giving frame to it. By this you can add as many number of tableview to a single class and no need to worry about data handling.
Put a frame to this table view, then you can add two frame to a view controller. So add this frame to your view controller, you should adjust the frame width and hight in order to show two tables.
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, (self.view.frame.size.width - 25 * 5), 54 * 5)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
tableView.showsVerticalScrollIndicator = true
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension LeftMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Home", "Features", "Pricing", "Help", "About Us", "Contact Us"] // put your titles
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty", "IconEmpty"] // add images if you want
cell.backgroundColor = UIColor.clearColor() // optional
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
case 1:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
default:
break
}
}
}
// MARK: UITextFieldDelegate Methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
return cell
}else{
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
}
return cell
}

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