TableView resizing - only when button clicks - ios

I am having some issues with my table view resizing - As it looks when the page loads :
And then once the button is clicked
As you can see, the button click renders the table to be of the correct size - how can I achieve this from the outset - as it makes it look much neater
My code for the class is as follows;
//
// FirstViewController.swift
// Intercultural Collaboration
//
// Created by Ricki Lambert on 06/10/2014.
// Copyright (c) 2014 com.kentapps. All rights reserved.
//
import UIKit
class QuizViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate{
var countries:Array<Answer> = [];
var selected = -1;
var positionOfSelected = 1;
#IBOutlet var next: UIBarButtonItem!
#IBOutlet var tableView: UITableView!
#IBAction func next(sender: AnyObject) {
}
func checkOkToProceed() -> Bool {
positionOfSelected = 1;
var result = false;
for answer in countries{
if(answer.selected){
result = true;
break;
}
positionOfSelected++;
}
return result;
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(sender.tag > 0 && !self.checkOkToProceed()){
//the user has not selected an answer so
//we need to show them a prompt
var alert = UIAlertController(title: "Unanswered Question", message: "Please select an answer!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil);
}
}
override func viewDidLoad() {
super.viewDidLoad();
tableView.reloadData();
//load answers to countries array
self.tableView.allowsMultipleSelection = false;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.countries.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = self.countries[indexPath.row].answerName;
cell.textLabel?.textAlignment = NSTextAlignment.Center;
let countryImage = String(self.countries[indexPath.row].answerName) + ".png";
cell.imageView?.image = UIImage(named: countryImage);
if(countries[indexPath.row].selected){
let imageName = "tick.png";
let image: UIImageView = UIImageView(image: UIImage(named: imageName));
cell.accessoryView = image;
}else{
let image: UIImageView = UIImageView();
cell.accessoryView = image;
}
tableView.sizeToFit();
return cell;
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
countries[indexPath.row].setSelected(true);
if(selected != -1){
countries[selected].setSelected(false);
}
selected = indexPath.row;
tableView.reloadData();
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == 0) {
//Do something
}
}
}

I recently had this issue. Here is an elegant solution:
tableView.tableFooterView = UIView()

Related

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

Swift - can't reload Data from TableView after add button action

I'm new to Swift and need your help.
I created a TableViewController with a custom cell.
Also I created a "add" Button in navigation bar to add a new value to my tableview.
Saving the values in Core Data and fetch them in viewWillAppear.
When pressing the add button a UIAlertController shows up which i had customized like i needed. I added a cancel action and a ok action but when i press the ok button from the alert the new value don't shows up in my tableview. I have to switch to an other viewcontroller that the tableview shows it.
I added groupsTableView.reloadData()on different points in my code but cant get it to work.
Hope someone can help me out!
Code from MasterViewController:
import UIKit
import CoreData
class MasterViewController: UITableViewController {
var groups: [Groups] = []
#IBOutlet weak var groupsTableView: UITableView!
var groupsTextField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
groupsTableView.delegate = self
groupsTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
// Core date initialization
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Groups> = Groups.fetchRequest()
do {
groups = try managedContext.fetch(fetchRequest)
groupsTableView.reloadData()
} catch {
// TODO: error handling
print("Could not fetch groups")
}
navigationItem.leftBarButtonItem = editButtonItem
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject))
navigationItem.rightBarButtonItem = addButton
}
// MARK: - add new Group
#objc func insertNewObject() {
let addButtonAlert = UIAlertController(title: "Neue Gruppe", message: "Füge eine neue Gruppe deiner Liste hinzu", preferredStyle: .alert)
addButtonAlert.addTextField { (UITextField) in
self.groupsTextField = UITextField
self.groupsTextField?.placeholder = "Name der Gruppe"
self.groupsTextField?.clearButtonMode = .whileEditing
}
let okAction = UIAlertAction(title: "Hinzufügen", style: .default, handler: addNewGroup)
let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil)
addButtonAlert.addAction(okAction)
addButtonAlert.addAction(cancelAction)
self.present(addButtonAlert, animated: true, completion: nil)
}
func addNewGroup(_:UIAlertAction) -> Void {
let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")
do {
try group?.managedObjectContext?.save()
groupsTableView.reloadData()
} catch {
// TODO: error handling
print("Could not save group")
}
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? DetailViewController,
let selectedRow = self.groupsTableView.indexPathForSelectedRow?.row else {
return
}
destination.group = groups[selectedRow]
destination.title = groups[selectedRow].groupTitle
}
// MARK: - delete Group
func deleteGroup(at indexPath: IndexPath) {
let group = groups[indexPath.row]
guard let managedContext = group.managedObjectContext else {
return
}
managedContext.delete(group)
do {
try managedContext.save()
groups.remove(at: indexPath.row)
groupsTableView.deleteRows(at: [indexPath], with: .automatic)
} catch {
//TODO: error handling
print("Could not delete Group")
groupsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groups.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = groupsTableView.dequeueReusableCell(withIdentifier: "GroupsTableViewCell", for: indexPath) as! GroupsTableViewCell
let object = groups[indexPath.row]
cell.groupTitleLabel?.text = object.groupTitle
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteGroup(at: indexPath)
}
}
}
Add group item to your groups array and after that reload your tableview as shown below:-
func addNewGroup(_:UIAlertAction) -> Void {
let group = Groups(groupId: UUID(), groupTitle: groupsTextField!.text ?? "")
do {
try group?.managedObjectContext?.save()
self.groups.append(group)
groupsTableView.reloadData()
} catch {
// TODO: error handling
print("Could not save group")
}
}

How to implement the "First In First Out" method in a UITableView?

I have implemented some Swift code to reveal cells labels one after the other in a tableView when the users swipes the screen.
To do so, I have a list of words stored in words and only its first item is visible in the tableView. Then, when the user swipes the screen, it sets the label of the next cell with the next word from words. Scrolling is enabled as words contains a long list of words.
In PlayViewController.swift, I handle the UITableView and the gestures while in PlayTableViewCell.swift, I set up the UITableViewCell. In ListViewController.swift, I ask the user what words he/she wants to store in the wordsarray.
PlayViewController.swift
class PlayViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var playTableView: UITableView!
var words = [String]()
var numberOfRevealedLabels = 1
var numberOfGoodAnswers = 0
var numberOfWrongAnswers = 0
var indexGA = 0
var indexWA = 0
override func viewDidLoad() {
super.viewDidLoad()
playTableView.delegate = self
playTableView.dataSource = self
self.playTableView.estimatedRowHeight = 50.0
view.isUserInteractionEnabled = true
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = .right
view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeLeft.direction = .left
view.addGestureRecognizer(swipeLeft)
}
// MARK: Table View Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "PlayTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlayTableViewCell else {
fatalError("The dequeued cell is not an instance of PlayTableViewCell.")
}
// Configure the cell...
cell.wordLabel.text = words[indexPath.row]
cell.wordLabel.isHidden = !(indexPath.row <= numberOfRevealedLabels - 1)
return cell
}
#objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizer.Direction.right:
indexGA = numberOfRevealedLabels
numberOfRevealedLabels += 1
numberOfGoodAnswers += 1
playTableView.reloadData()
case UISwipeGestureRecognizer.Direction.left:
indexWA = numberOfRevealedLabels
numberOfRevealedLabels += 1
numberOfWrongAnswers += 1
playTableView.reloadData()
default:
break
}
}
}
}
PlayTableViewCell.swift
class PlayTableViewCell: UITableViewCell {
//MARK: Properties
#IBOutlet weak var wordLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
wordLabel.lineBreakMode = .byWordWrapping;
wordLabel.numberOfLines = 0;
wordLabel.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ListViewController.swift
class ListViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var titleTextField: UITextField!
#IBOutlet weak var nametextField: UITextField!
#IBOutlet weak var dataTableView: UITableView!
#IBOutlet weak var saveButton: UIBarButtonItem!
var data = [String]()
//MARK: Properties
var list: List?
//MARK: ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input through delegate callbacks.
titleTextField.delegate = self
nametextField.delegate = self
// Set up views if editing an existing List.
if let list = list {
navigationItem.title = list.name
titleTextField.text = list.name
data = list.content
}
// Enable the Save button only if the title field has a valid List name
updateSaveButtonState()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addNameToTable(_ sender: Any) {
guard let word = nametextField.text else {
return
}
data.append(word)
dataTableView.reloadData()
}
#IBAction func playGame(_ sender: Any) {
}
//MARK: UITextFieldDelegate
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable the Save button while editing
if (textField == titleTextField) {
saveButton.isEnabled = false
} else {
saveButton.isEnabled = true
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateSaveButtonState()
navigationItem.title = titleTextField.text
guard let word = nametextField.text else {
return
}
if (textField == nametextField) {
data.append(word)
dataTableView.reloadData()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
//MARK: Navigation
#IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
let isPresentingInAddListMode = presentingViewController is UINavigationController
if isPresentingInAddListMode {
dismiss(animated: true, completion: nil)
} else if let owningNavigationController = navigationController{
owningNavigationController.popViewController(animated: true)
} else {
fatalError("The ListViewController is not inside a navigation controller.")
}
}
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "playGame") {
// Passing words list to the PlayViewController
let detailVC = segue.destination as! PlayViewController;
detailVC.words = data
}
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = titleTextField.text ?? ""
list = List(name: name, content: data)
}
//MARK: Private Methods
private func updateSaveButtonState() {
// Disable the Save button if the text field is empty.
let name = titleTextField.text ?? ""
saveButton.isEnabled = !name.isEmpty
}
}
//MARK: Extension
extension ListViewController : UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}// Default is 1 if not implemented
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell!.textLabel?.text = data[indexPath.row]
return cell!
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return 50
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
let alert = UIAlertController(title: "", message: "Edit list item", preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
textField.text = self.data[indexPath.row]
})
alert.addAction(UIAlertAction(title: "Update", style: .default, handler: { (updateAction) in
self.data[indexPath.row] = alert.textFields!.first!.text!
self.dataTableView.reloadRows(at: [indexPath], with: .fade)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: false)
})
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
self.data.remove(at: indexPath.row)
self.dataTableView.reloadData()
})
return [deleteAction, editAction]
}
}
And it works fine.
Now, I'd like to prompt each item of words FIFO-style (First In First Out) in a tableView with a fixed number of rows.
Let's say I have a 3-rows tableView:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
And words contains 5 items:
word1
word2
word3
word4
word5
I'd like to display each of them in this order:
First word Second word Third word Fourth word Fifth word
------------ ------------ ------------ ------------ ------------
| word1 | | word1 | | word1 | | word2 | | word3 |
------------ ------------ ------------ ------------ ------------
| | | word2 | | word2 | | word3 | | word4 |
------------ ------------ ------------ ------------ ------------
| | | | | word3 | | word4 | | word5 |
------------ ------------ ------------ ------------ ------------
What changes do I need to implement in PlayViewController.swift to recreate this FIFO animation?
My goal here is to eliminate the scrolling and make it easier to read, and also to help the swipes as they seem to be undetectable when performed over a scrollable tableView.
I'm not sure if I need to rewrite a bigger part of my code or changing a few lines in PlayViewController.swift could do the trick.
Thanks for your help!

ViewCell height doesnt work Swift 4

I'm beginner at Xcode and I need some help with viewcell in table view.
This is the properties for my viewcell:
When i tried to run the simulator it become something like this:
my viewcontroller
import UIKit
import SwiftyJSON
import Kingfisher
class CakeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//MARK : Properties
var cakeArray = [Cake]()
#IBOutlet weak var testImage: UIImageView!
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cakeArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CakeTableViewCell"
// let cell = tableView.dequeueReusableCell(withIdentifier: "CakeCategoryTableViewCell"/*Identifier*/, for: indexPath)
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? CakeTableViewCell else {
fatalError("The dequeued cell is not an instance of cakeViewCell.")
}
//cell.textLabel?.text = cake_category[indexPath.row]
let cakeObj = cakeArray[indexPath.row]
cell.cakeLabel.text = cakeObj.product
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
print("Load Initial Data")
loadInitialDataFromJson(category : "Reguler Cake")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadInitialDataFromJson(category:String)
{
APIManager.sharedInstance.getCakeByCategory(category: category, onSuccess: {json in DispatchQueue.main.async {
let status = json["status"].stringValue
//let message = json["message"].stringValue
if status == "OK"
{
for (key, subJson) in json["list_produk"] {
//print(subJson["id_product"])
var arrayVariant = [Variant]()
for(key,subsJson) in subJson{
arrayVariant.append(Variant(size:subsJson["size"].stringValue,price:subsJson["price"].intValue)!)
}
self.cakeArray.append(Cake(id_product:subJson["id_product"].stringValue,product:subJson["product"].stringValue,description:subJson["description"].stringValue,imageURL:subJson["images"].stringValue,variant:arrayVariant)!)
}
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 150
self.tableView.reloadData()
}else{
print("Not Ok")
}
}}, onFailure: {error in let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.show(alert, sender: nil)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
and my tableviewcell
import UIKit
class CakeTableViewCell: UITableViewCell {
// MARK : Properties
#IBOutlet weak var cakeImage: UIImageView!
#IBOutlet weak var cakeLabel: UILabel!
#IBAction func addToCart(_ sender: 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
}
}
Any idea why this happening??
I've created some views with tableview and it has worked normally.
to adjust your cell hight call in your cakeViewController
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100.0;//Choose your custom row height
}

UITableView is reloaded when presentviewcontroller or pushviewcontroller

I have a uitableview with some complex cells,
If I do presentviewcontroller or pushviewcontroller when I press the button in the cell,
it will reload data automatically,
how can i stop it?
this is the base Controller
import UIKit
class Controller: UIViewController{
override func viewDidLoad() {
super.viewDidLoad();
initView();
}
func initView(){
self.view.backgroundColor = UIColor.whiteColor();
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
}
and this is the second level
import Foundation
class LoadableController: Controller {
var requestNum : Int = 0;
func loadData(complete: (()->Void)? = nil){
self.requestComplete();
}
func requestComplete(){
if(self.requestNum == 0){
requestFinished();
return;
}
self.requestNum = self.requestNum > 0 ? self.requestNum - 1 : 0;
if(self.requestNum == 0){
requestFinished();
}
}
func requestFinished(){}
}
this is the third level
class TableListViewController: LoadableController, UITableViewDelegate, UITableViewDataSource {
var tableView : UITableView?;
var curPage : Int = 0;
var totalPage : Int = 0;
override func viewDidLoad() {
super.viewDidLoad()
}
override func initView() {
super.initView();
tableView = UITableView();
tableView!.delegate = self;
tableView!.dataSource = self;
tableView!.delaysContentTouches = false;
tableView!.canCancelContentTouches = true;
self.view.addSubview(tableView!);
tableView!.snp_makeConstraints { [unowned self](make) in
make.edges.equalTo(self.view);
}
let header = EGRefresh(refreshingTarget: self, refreshingAction: #selector(self.loadData));
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Idle);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Pulling);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .WillRefresh);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Refreshing);
header.lastUpdatedTimeLabel.hidden = true;
tableView!.mj_header = header;
let footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(self.loadNext));
tableView!.mj_footer = footer;
}
func loadNext(){
tableView!.mj_footer.endRefreshing();
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath);
return cell;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func requestFinished() {
tableView!.mj_header.endRefreshing();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
DDLogInfo("TableListViewController deinit");
}
}
and here is the place where the tableview reload automatically.
import UIKit
class CircleViewController: TableListViewController {
override func viewDidLoad() {
super.viewDidLoad();
}
override func initView(){
super.initView();
self.title = "Circle";
let items = ["One", "Two"];
let segment = UISegmentedControl(items: items);
segment.selectedSegmentIndex = 0;
segment.setWidth(80, forSegmentAtIndex: 0);
segment.setWidth(80, forSegmentAtIndex: 1);
self.navigationItem.titleView = segment;
tableView!.estimatedRowHeight = 50;
tableView!.rowHeight = UITableViewAutomaticDimension;
// tableView!.contentInset = UIEdgeInsetsMake(Dimens.TopBarHeight, 0, 0, 0);
tableView!.registerClass(TextOnlyCell.self, forCellReuseIdentifier: "CircleTextOnlyCell");
tableView!.registerClass(ImageAndPageCell.self, forCellReuseIdentifier: "CircleImageAndPageCell");
Event.addEventListener(self, selector: #selector(self.goComment(_:)), name: EventType.CIRCLE_COMMENT, object: nil);
}
func goComment(ns: NSNotification) {
let commentView = PostCommentViewController();
self.navigationController?.pushViewController(commentView, animated: true);
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CircleImageAndPageCell", forIndexPath: indexPath) as? ImageAndPageCell;
if cell == nil {
cell = ImageAndPageCell.init(style: .Default, reuseIdentifier: "CircleImageAndPageCell");
}
let images = [UIImage(named: "b.jpg")!, UIImage(named: "a.jpg")!, UIImage(named: "c.jpg")!, UIImage(named: "a.jpg")!];
cell?.initView(nil, nickname: "im a nickname", time: "10 min", content: NSMutableAttributedString(string: "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf"), likeNum: 10, commentNum: 12, shareNum: 13, totalLine: 20, images: images, cellIndex: indexPath.row, hasPage: true, pageIcon: UIImage(named: "c.jpg")!, titleStr: "ahahaha");
return cell!;
}
override func loadData(complete: (() -> Void)?) {
self.requestComplete();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
Event.removeAllEventListener(self);
DDLogInfo("CircleViewController deinit");
}
}
If goComment be called,
the viewcontroller will be pushed,
then the tableview will jump to top,
I add a break point to the cellForRowAtIndexPath,
it's called.
then I tried the presentviewcontroller,
this problem also happened,
even though I did presentviewcontroller in the outside viewcontroller.
it seems not reload data,
it's just scrolls to the top.
it's looking like table view not taking the uitoolbar size(44 points) in account
Save the tableview offset in prepareForSegue: (save it in a CGPoint property)
self.tableViewScrollOffset = self.tableView.contentOffset;
Then, in viewWillAppear:, check if it has been modified. If so, restore it.
if(self.tableView.contentOffset.y != self.tableViewScrollOffset.y) {
[self.tableView setContentOffset:self.tableViewScrollOffset];
self.tableViewScrollOffset = CGPointZero;
}

Resources