Table View is not reflecting change in size - swift

//
// ViewController.swift
// practise
//
// Created by ali on 29/11/2019.
// Copyright © 2019 smartsolution. All rights reserved.
//
import UIKit
class nestedviewcontroller: UIViewController {
var maindatacells:[String]=["m1","m2","m3","m9"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension nestedviewcontroller:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.rowHeight = UITableView.automaticDimension
return maindatacells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! maintablecell
cell.lbltitle.text = maindatacells[indexPath.row]
cell.setdata(cont: self)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
var height = cell.frame.height
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
var heightjjj = cell.frame.height
}
}
class maintablecell:UITableViewCell,UITableViewDelegate,UITableViewDataSource{
#IBOutlet weak var tblheightconstraint:NSLayoutConstraint!
#IBOutlet weak var lbltitle:UILabel!
#IBOutlet weak var tblinside:UITableView!
var cellheight:CGFloat = 20
var parentcont:UIViewController!
override func awakeFromNib() {
super.awakeFromNib()
tblinside.delegate = self
tblinside.dataSource = self
}
func setdata(cont:UIViewController){
self.parentcont = cont
}
var datacells = ["i1","i2","i3","67"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datacells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = datacells[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0{
cellheight = 0
}
cellheight += cell.contentView.frame.height
if indexPath.row == datacells.count - 1{
// var tbl = self.superview as! UITableView
// tblinside.estimatedRowHeight = cellheight
// tbl.estimatedRowHeight = cellheight
tblheightconstraint.constant = cellheight
tblinside.beginUpdates()
tblinside.endUpdates()
self.setNeedsDisplay()
self.setNeedsLayout()
self.setNeedsUpdateConstraints()
self.parentcont.view.setNeedsLayout()
self.parentcont.view.setNeedsDisplay()
// var siz = self.frame.size
// //
// self.frame.size = CGSize(width: siz.width, height: siz.height + 30)
}
}
}
I am updating tableview size programmaticaly by changing its constraint. But tableview is not reflecting the change untill i refresh tableview by scrolling.I have tried many functions to update layout of main cell or tableview but i didnt find anything helping.
The tableview resize perfectly when i scroll the maintableview and the cell freshes

Related

Multiple headerview in tableview in swift

I want to create 3 headers in the tableview given in the images and 8 students in each row, my code is as follows
Screenshot of the example
class ViewController: UIViewController {
var schoolOfList: [Any] = [
[["school": ["VIP", "Bright International", "Motherland"]],
[["student1": ["Chirag", "Akshay", "Shailesh", "Vishal", "Mehul", "Vinod", "Mukesh", "Darshan"]],
["student2": ["Manjari", "Kairav", "Abhimanyu", "Akshara", "Arohi", "Neel", "Naksh", "Naman"]],
["student3": ["Paritosh", "Anuj", "Kavya", "Samar", "Vanraj", "Kinjal", "Anupama", "Riyan"]]]]]
#IBOutlet weak var mytableview : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> (Int) {
return schoolOfList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
cell.textLabel?.text = schoolOfList["school"] as! [String]indexPath.row
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerview = UIView(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
headerview.backgroundColor = .green
let lable = UILabel(frame: CGRect(x:0,y:0,width:self.mytableview.frame.width,height:50))
lable.textAlignment = .center
lable.text = (schoolOfList["school"]as!String)
headerview.addSubview(lable)
return headerview
}

Disable users to scroll up in tableView?

Similar to tinder, if a user goes down, I don't want them to be able to go back upwards. How do I do this?
I tried the code below, but it keeps running an error: Index out of range.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! FeedTableViewCell
cell.collectionView.delegate = self
cell.collectionView.dataSource = self
//reloading the tableview
let artist: UserModel
artist = self.userList[indexPath.row]
cell.nameLabel.text = artist.name
cell.passionLabel.text = artist.passion
cell.collectionView.reloadData()
if indexPath.row == 1 {
userList.removeFirst()
}
return cell
}
Refer below code,
You need to store last scroll Content Offset of tableview, when user scroll down, refer scrollViewDidScroll method.
#IBOutlet weak var tableView: UITableView!
var lastContentOffsetY:CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.bounces = false
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuse")
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuse")
return cell!
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if(scrollView.contentOffset.y < self.lastContentOffsetY){
self.tableView.setContentOffset(CGPoint(x:scrollView.contentOffset.x, y: self.lastContentOffsetY), animated: false)
}else{
self.lastContentOffsetY = scrollView.contentOffset.y
}
}

Inserting a table view row data from another table view?

So I have two table views. MainTableView and SecondaryTableView, The MainTableView has empty rows with no text. A Table view cell is configured though. These rows have the option to delete. The SecondaryTableView rows also have an editing style in which I am using to ADD the selected row into the MainTableView rows.
class MainVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet var mycartableview: UITableView!
var passedcar = String()
override func viewDidLoad() {
super.viewDidLoad()
mycartableview.tableFooterView = UIView(frame: CGRect.zero)
}
var diynames: [String] = ["a","b","c"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diynames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let diyname = diynames[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "mycarcell") as! mycarcell
cell.mycartitle.text = diyname
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
diynames.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
SecondaryVC code:
class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
let names = ["aa","ba","ca","da","ea",]
#IBOutlet var tableview: UITableView!
#IBOutlet var slctedcar: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.backgroundColor = .white
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "diylistcell") as! diylistcellTableViewCell
cell.diytitle.text = names[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let addbutton = UITableViewRowAction(style: .normal, title: "Add") { (rowAction, indexpath
) in
print("Add clicked")
let mycarvc = MyCarViewController()
mycarvc.diynames.append(contentsOf: self.hcdiynames)
let hcindexpath = IndexPath(row: mycarvc.diynames.count - 1, section: 0)
mycarvc.mycartableview.insertRows(at: [hcindexpath], with: .automatic) //this is where the error occurs. Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
mycarvc.mycartableview.endUpdates()
}
addbutton.backgroundColor = UIColor.darkGray
return [addbutton]
}
Clear Image of Error
That's where my pain is coming from. As you could see in the picture above the highlighted area it says that my array coming from the main vc is a count of 8. That checks out completely because the original array has 3 and I am appending 5 new ones. The error implicitly found nil has left me clueless in this scenario. If anybody has any suggestions on how to fix this problem it would be highly appreciated, thank you .
This is a common error when you try to transfer data between VC , I usually create 1 variable which will store what I want and after in the viewDidLoad() I give the value of this variable to what I really want , IN your code the equivalent is
class MainVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet var mycartableview: UITableView!
var passedcar = String()
// I JUST CREATED THE VARIABLE WHICH WILL HOLD OUR VALUES
var diynamesContainer = [String]()
///////////////////
var diynames: [String] = ["a","b","c"]
override func viewDidLoad() {
super.viewDidLoad()
mycartableview.tableFooterView = UIView(frame: CGRect.zero)
// I ADD TO OUR ARRAY THE VALUE OF THE diynamesContainer
diynames.append(contentsOf: diynamesContainer)
//////////////////
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diynames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let diyname = diynames[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "mycarcell") as! mycarcell
cell.mycartitle.text = diyname
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
diynames.remove(at: indexPath.row)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
/*
// MARK: - Navigation
and in our main vc you replace
let mycarvc = MyCarViewController()
mycarvc.diynames.append(contentsOf: self.hcdiynames)
by
let mycarvc = MyCarViewController()
mycarvc.diynamesContainer = self.hcdiynames
Try to run your code, the error will go away

Change label text when height expand of cell of tableView in swift

I am new in IOS and i am using swift.I want to change the text of label when height of cell expand.Please tell me how to change text when height expand of cell in swift.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
var selectedIndex = -1
var height = 54
// Data model: These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
// don't forget to hook this up from the storyboard
#IBOutlet var tableView: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// create a new cell if needed or reuse an old one
let cell:Cell1 = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell1!
cell.textLabel?.text = "-"
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell:Cell1 = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell1!
if(selectedIndex == indexPath.row)
{
height = 216
cell.textLabel?.text = "+"
}else{
height = 54
cell.textLabel?.text = "/"
}
return CGFloat(height)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print("You tapped cell number \(indexPath.row).")
if(selectedIndex == indexPath.row)
{
selectedIndex = -1
}
else
{
selectedIndex = indexPath.row
}
}
}
In your code you are trying to dequeue the cell again in your heightForRowAt function, I think that's your issue.
so try replace your heightForRowAt function with the below code.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = tableView.cellForRow(at: indexPath)
if(selectedIndex == indexPath.row)
{
height = 216
cell.textLabel?.text = "+"
}else{
height = 54
cell.textLabel?.text = "/"
}
return CGFloat(height)
}

How to make label or image dynamic in tableviewcell?

I want to make tableview cell have dynamic label or image in it. I don't want to loop add subview to content view of tableview cell because it will run slow when you scroll. So can anyone help me please? Like this image:
My code is;
Without knowing the context of your code, something like this can work:
NOTE This will work on iOS <= 8
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var TableVC: UITableView!
let elements = ["item1 item2 item3","item1 item2", "item1"]
override func viewDidLoad() {
super.viewDidLoad()
self.TableVC.delegate = self
self.TableVC.dataSource = self
self.TableVC.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.attributedText = addTextToAttribute(text: elements[indexPath.item])
return cell
}
func addTextToAttribute(text : String) -> NSMutableAttributedString {
let mutString = NSMutableAttributedString()
let s = text.components(separatedBy: .whitespaces)
let attr: [String: AnyObject] = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)]
for text in s {
mutString.append(NSAttributedString(string: "-" + text + "\n", attributes: attr))
}
return mutString
}
}