How to make dynamic height of UITableViewCell - ios

I would like to create dynamic height of UITableViewCell depending tablecell content.
But i couldn't.
import UIKit
class WorkItemCell: UITableViewCell{
#IBOutlet weak var item_view: UIView!
#IBOutlet weak var minimum_startday_label: CustomLabel!
#IBOutlet weak var catchcopyLabel: CustomLabel!
#IBOutlet weak var stationLabel: UILabel!
#IBOutlet weak var paymentLabel: UILabel!
#IBOutlet weak var limitLabel: UILabel!
#IBOutlet weak var mainjobLabel: UILabel!
#IBOutlet weak var companyLabel: UILabel!
#IBOutlet weak var workstartdateLabel2: UILabel!
#IBOutlet weak var fav_view: ImageWithView!
#IBOutlet weak var img_seen_view: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//self.fav_view = ImageWithView.instance()
self.fav_view.checkedImage = UIImage(named: "fav_on")
self.fav_view.uncheckedImage = UIImage(named: "fav_off")
}
override func layoutSubviews() {
super.layoutSubviews()
self.contentView.layoutIfNeeded()
self.catchcopyLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.catchcopyLabel.bounds)
}
private var _workdic: NSDictionary?
var workdic: NSDictionary? {
get {
return _workdic
}
set(workdic) {
_workdic = workdic
if let workdic = workdic {
let workplace = workdic["WorkPlace"] as? String
let companyname = workdic["CompanyName"] as? String
let jobname = workdic["JobName"] as? String
let payment = workdic["Payment"] as? String
let workstartdate = workdic["WorkStartDate"] as? String
let workdatetime = workdic["WorkDateTime"] as? String
let minimumday = workdic["MinimumWorkDay"] as? String
let applyenddate = workdic["ApplyEndDate"] as? String
let catchcopy = workdic["CatchCopy"] as? String
if notnullCheck(catchcopy){
//行間
let attributedText = NSMutableAttributedString(string: catchcopy!)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedText.length))
self.catchcopyLabel.attributedText = attributedText
}
self.catchcopyLabel.sizeToFit()
if let payment_constant = payment{
self.paymentLabel.text = payment_constant
}
if notnullCheck(minimumday) && notnullCheck(workstartdate){
self.minimum_startday_label.text = minimumday!+" "+workstartdate!
}else{
self.minimum_startday_label.text = ""
}
if let applyenddate_constant = applyenddate{
self.limitLabel.text = applyenddate_constant
}
if let jobname_constant = jobname{
self.mainjobLabel.text = jobname_constant
}
if let workdatetime_constant = workdatetime{
self.workstartdateLabel2.text = workdatetime_constant
}
if let companyname_constant = companyname{
self.companyLabel.text = companyname_constant
}
self.stationLabel.text = workplace
self.item_view.sizeToFit()
}
}
}
class func heightForRow(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
struct Sizing {
static var cell: WorkItemCell?
}
if Sizing.cell == nil {
Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
}
if let cell = Sizing.cell {
cell.frame.size.width = CGRectGetWidth(tableView.bounds)
cell.workdic = workdic
cell.setNeedsDisplay()
cell.layoutIfNeeded()
let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
print(size)
return size.height+1
}
return 0
}
}
Above code has item_view.
It has all label and image.
It is setted margin at 4 points(top,left,bottom,right),5px.
I use above cell for data list.
It has around 5000 counts.
Catch copy label is often setted 2 line sentence.
I want to change item_view height and cell height each catch_copy_label's height.
But I couldn't.
I always have gotten same height,26px.
(366.5, 26.0)
(366.5, 26.0)
What should i do?
I have add the part of view controller's source.
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
if self.int_total == 0{
return self.view.frame.size.height
}else{
if let workdic: AnyObject = workdata.safeObjectAtIndex(indexPath.row){
return WorkItemCell.heightForRow(self.workview, workdic: (workdic as! NSDictionary),base_height:170)
}else{
return 199
}
}
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 199
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.int_total == 0{
return 1
}
return self.workdata.count
}
/*
Cellに値を設定する.
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Cellの.を取得する.
if self.int_total > 0{
let cell = workItemCell(tableView, cellForRowAtIndexPath: indexPath, str_xib: "WorkItemCell")
return cell
}else{
let nocell: NoCountCell = tableView.dequeueReusableCellWithIdentifier("NoCountCell", forIndexPath: indexPath) as! NoCountCell
nocell.conditionButton.addTarget(self, action: "onClickBack:", forControlEvents: .TouchUpInside)
//初期が終わったらfalse
if self.init_loading{
nocell.conditionButton.hidden = true
nocell.messageLabel.hidden = true
}else{
nocell.conditionButton.hidden = true
nocell.messageLabel.hidden = false
}
return nocell
}
}
func workItemCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath,str_xib:String) ->WorkItemCell{
let wcell: WorkItemCell = tableView.dequeueReusableCellWithIdentifier(str_xib, forIndexPath: indexPath) as! WorkItemCell
wcell.separatorInset = UIEdgeInsetsZero
wcell.selectionStyle = UITableViewCellSelectionStyle.None
updateCell(wcell, atIndexPath: indexPath)
return wcell
}
func updateCell(cell:UITableViewCell,atIndexPath:NSIndexPath){
}
func showWorkItem(wcell:WorkItemCell,workdic:NSDictionary){
wcell.workdic = workdic
}
I have posted capture.

This is in Objective C.Calculate the height of cell's content in heightForRowAtIndexPath method add it in one array as
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
text =[NSString stringWithFormat:#"%#",[content_array objectAtIndex:indexPath.row]];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tblView.frame.size.width - PADDING * 3, 1000.0f)];
NSLog(#"%f",textSize.height);
[height_Array addObject:[NSString stringWithFormat:#"%f", textSize.height]];
return textSize.height;
}
Now in cellForRowAtIndexPath method set the frame of title using height array as:-
CGRect newFrame = txtTitle.frame;
newFrame.size.height = [[height_Array objectAtIndex:indexPath.row] floatValue];
txtTitle.frame = newFrame;

I finaly got answer.
But i have calculated height manually.
I calculated the label's height at each time.
This label has multi line.
Then I set height other height + the height which was calcuted.
class func heightForCatchCopy(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
struct Sizing {
static var cell: WorkItemCell?
}
if Sizing.cell == nil {
Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
}
if let cell = Sizing.cell {
cell.frame.size.width = CGRectGetWidth(tableView.bounds)
cell.workdic = workdic
let size = cell.catchcopyLabel.intrinsicContentSize()
return size.height
}
return 0
}

Related

How to increment and decrement value of label in tableview and make total price from label value in swift?

now cell value are dynamically and its look after calling api.
I want to make total of all tickets price at last. I refer this link How do I increment/decrement a label value with two buttons pressed in tableview Swift and make changes in my code but didn't work for me.
struct Product {
var price = 0
}
class TicketBookingVC: UIViewController , UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblView: UITableView!
#IBOutlet weak var mainTblView: UIView!
var bookingDetails = NSDictionary()
var productArray = [Product]()
var product : Product!
private var counterValue = 1
var productIndex = 0
var counterLbl = UILabel()
#IBOutlet weak var bookBtn: UIButton!
#IBOutlet weak var eventImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
for _ in 0...10{
productArray.append(Product(price: 1))
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else if section == 1{
return 4
}
else{
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellfirst", for: indexPath)
cell.selectionStyle = .none
return cell
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellsecond", for: indexPath)
let mainViewCell = cell.contentView.viewWithTag(2000) as! UIView
let normalView = cell.contentView.viewWithTag(2001) as! UIView
let eventName = cell.contentView.viewWithTag(2003) as! UILabel
let eventPrice = cell.contentView.viewWithTag(2004) as! UILabel
counterLbl = cell.contentView.viewWithTag(2007) as! UILabel
let decrementBtn = cell.contentView.viewWithTag(2005) as! UIButton
let incrementBtn = cell.contentView.viewWithTag(2006) as! UIButton
decrementBtn.addTarget(self, action:#selector(self.decrementbuttonClicked), for: .touchUpInside)
incrementBtn.addTarget(self, action:#selector(self.incrementbuttonClicked), for: .touchUpInside)
product = productArray[indexPath.row]
counterLbl.text = "\(product.price)"
cell.selectionStyle = .none
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellthird", for: indexPath)
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0{
return UITableView.automaticDimension
}
else{
return 80
//return UITableView.automaticDimension
}
}
#objc func decrementbuttonClicked() {
print("Button decrement")
if(counterValue != 1){
counterValue -= 1;
}
self.counterLbl.text = "\(counterValue)"
product.price = counterValue
}
#objc func incrementbuttonClicked() {
counterValue += 1;
self.counterLbl.text = "\(counterValue)"
product.price = counterValue
}
func addProductToCart(product: Product, atindex: Int) {
productArray[atindex] = product
calculateTotal()
}
func calculateTotal()
{
var totalValue = 0
for objProduct in productArray {
totalValue += objProduct.price
}
self.eventPrice.text = "Total \(totalValue)"
}
}
when I increment or decrement value of first cell it reflect in 4th cell. please help. I am new at swift.
This is due to cell reuse. You should set a model for each cell

Swift hide/show UIView in cell (data from database)

I have UITableViewCell with UITextView and UIView
I'm try to hide/show UIView
Constraints — TextView:
Trailing to Superview Equals 2
Leading to Superview Equals 2
Top to Superview Equals 2
Bottom to Superview Equals 40
UIVIew:
Trailing to Superview
Leading to Superview
Bottom to Superview
Height 35
In Cell class I'm connect TextView BottomConstraint
UITableViewCell class :
#IBOutlet weak var myTextView: UITextView!
#IBOutlet weak var detailView: UIView!
#IBOutlet weak var detailLabel: UILabel!
#IBOutlet weak var TextViewConstraintToBottom: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
detailView.isHidden = true
if detailView.isHidden == true {
TextViewConstraintToBottom.constant = 0
} else {
TextViewConstraintToBottom.constant = 40
}
}
In ViewController with UITableView :
var handle: DatabaseHandle?
var ref: DatabaseReference?
var quoteList: [String] = []
var songArray: [String] = []
override func viewWillAppear(_ animated: Bool) {
myTableView.estimatedRowHeight = 100
myTableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
dataCatch()
}
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if let us = username?["song"].unsafelyUnwrapped {
self.celT?.detailView.isHidden = false
self.songArray.append(us as! String)
self.myTableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
let indexP = indexPath.row
cell.myTextView.text = quoteList[indexP]
cell.detailLabel.text = songArray[indexP]
return cell
}
In database I have structure
I decided
In ViewController :
func dataCatch() {
ref = Database.database().reference()
handle = ref?.child("Цитаты").child("\(cat)").child("\(quoteNAme)").observe(.childAdded, with: { (snapshot) in
let username = snapshot.value as? NSDictionary
if let us = username?["name"] {
self.quoteList.append(us as! String)
self.quoteList = self.quoteList.filter(){$0 != "1"}
self.myTableView.reloadData()
}
if snapshot.hasChild("song") {
let us = username?["song"]
self.songArray.append(us as! String)
} else {
let tet = "1"
// self.celT?.detailView.isHidden = true
self.songArray.append(tet as! String)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.detailLabel.text = songArray[indexP]
if cell.detailLabel.text != "1" {
cell.detailView.isHidden = false
cell.butConstraint.constant = 40
} else {
cell.detailView.isHidden = true
cell.butConstraint.constant = 0
}
In cellForRow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UI TableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuoteTableVC
// hide = check your model whether it has song or not
if hide {
cell.TextViewConstraintToBottom.constant = 0
}
else {
cell.TextViewConstraintToBottom.constant = 40
}
}

iOS Scrolling Parallax Effect in Table View Cell Swift 4

I create Scrolling Parallax Effect in Table View Cell in my project but i have some freeze when i scrolling.
My code in custom Table View Cell :
class newsTableViewCell: UITableViewCell {
#IBOutlet weak var imageNews: UIImageView!
#IBOutlet weak var titleLable: UILabel!
#IBOutlet weak var imageHeight: NSLayoutConstraint!
#IBOutlet weak var imageTop: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
imageNews.clipsToBounds = true
}
}
Code in my Main View Controller:
var paralaxOfSetSpeed: CGFloat = 70
var cellHeignt: CGFloat = 170
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! newsTableViewCell
let good = data[indexPath.row]
cell.titleLable.text = (good["title"] as! String)
cell.imageHeight.constant = paralaxImageHeight
cell.imageTop.constant = paralaxOfSet(newOfSetY: tableView.contentOffset.y, cell: cell)
let newsImage = good["image"] as! PFFile
newsImage.getDataInBackground{ (imageData, error) in
if imageData != nil {
let image = UIImage(data: imageData!)
cell.imageNews.image = image
} else {
print(error ?? "getDataInBackground error")
}
}
return cell
}
func paralaxOfSet(newOfSetY: CGFloat, cell: UITableViewCell) -> CGFloat {
return (newOfSetY - cell.frame.origin.y) / paralaxImageHeight * paralaxOfSetSpeed
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let ofSetY = tableView.contentOffset.y
for cell in tableView.visibleCells as! [newsTableViewCell] {
cell.imageTop.constant = paralaxOfSet(newOfSetY: tableView.contentOffset.y, cell: cell)
}
}
var paralaxImageHeight: CGFloat {
let maxOffSet = (sqrt(pow(cellHeignt, 2) + 4 * paralaxOfSetSpeed * self.tableView.frame.height ) - cellHeignt) / 1.5
return maxOffSet + self.cellHeignt
}
This is my code, main problem it's scrolling because it's a not smooth.
UPDATE:
So in the end, i want to get something like this:
I would suggest you to look into the below libraries:
They have implemented the parallax view in TableViewCell
https://github.com/marty-suzuki/SAParallaxViewControllerSwift
Hope it helps.

Updating Constraints in UITableViewCell are not properly

I want to make a dynamic cell in my UITableView in case of image height. Everything works properly, but when I scroll my UITableView, debugger is yelling me about bad constraints in my cell, but cells look exactly what I want. I can't be calm when I see this debug info ;)
My CustomCell class looks like that:
class CustomCell: UITableViewCell {
//MARK: - Outlets
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var heightConstraint: NSLayoutConstraint!
//MARK: - Variables
var dream: MyDream? {
didSet {
if let item = dream, let image = UIImage(data: item.photoData) {
scaleImageView(image: image)
photoImageView.image = image
titleLabel.text = item.title
}
}
}
func scaleImageView(image: UIImage) {
let imageWidth = image.size.width
let imageScale = image.size.height / image.size.width
if imageWidth > photoImageView.bounds.width {
heightConstraint.constant = photoImageView.bounds.size.width * imageScale
} else {
heightConstraint.constant = imageWidth * imageScale
}
}
}
my cell in .xib looks like that:
TitleLabel doesn't have a height constraint. Leading, Top, Trailing, Bottom only.
and my ViewController is quite simple and looks like that:
class ViewController: UIViewController {
//MARK: - Outlets
#IBOutlet var tableView: UITableView!
//MARK: - Variables
lazy var dreams = [MyDream]()
override func viewDidLoad() {
super.viewDidLoad()
createModel() // I mock data here :)
setTableView()
}
func setTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(UINib(nibName: String(describing: CustomCell.self), bundle: nil), forCellReuseIdentifier: "cell")
}
func createModel() {
for i in 0..<12 {
if i < 6 {
if let image = UIImage(named: "\(i + 1)"), let imageData = UIImageJPEGRepresentation(image, 100) {
let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
dreams.append(dream)
}
} else {
if let image = UIImage(named: "\(i - 5)"), let imageData = UIImageJPEGRepresentation(image, 100) {
let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
dreams.append(dream)
}
}
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dreams.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.dream = dreams[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
How it looks like in simulator:
every thing look fine, but console gives me this kind of error:
I don't know why? I tried to use layoutIfNeeded(), updateConstraints() and setNeedsLayout() in didSet in CustomCell but is doesn't help. Any suggestions?
I guess you're having some redundant constraints on your image.
They could be height / bottom / top constraints. One should be removed

UITableView Height is not correct dynamically some time using Swift and without AutoLayout

Really I have one issue about set UITableView Height Dynamically correct. I am not using AutoLayout. First time when table Loaded, It contains lots of space top and bottom of the cell and some time images are overlapping with other cells. I am unable to calculate the right height of cell due to images (image can be large in height )Below is code.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeight
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:Templategt4 = tableView.dequeueReusableCell(withIdentifier: "Templategt4Identify", for: indexPath) as! Templategt4
cell.delegate = self;
cell.configure( self.storyData[0], row: indexPath, screenSize: screenSize,
gt4tableview: self.storyTableView);
//self.secondWebViewLable.scrollView.contentSize.height
cellHeight = cell.firstWebViewLable.frame.height + cell.firstImage.frame.height + cell.secondWebViewLable.frame.height;
//cellHeight = cellHeight + 200
print("cellForRowAt cellHeight", cellHeight);
return cell
}
I am using Custom Cell. The cell contains to UiWebView, UIImageView ( Height can be too much long ). Below is the code of cell.
class Templategt4: UITableViewCell, UIWebViewDelegate{
#IBOutlet weak var firstWebViewLable: UIWebView!
#IBOutlet weak var firstImage: UIImageView!
#IBOutlet weak var secondWebViewLable: UIWebView!
#IBOutlet weak var playiconimage: UIImageView!
let padding = 24;
var contentHeights1 : [CGFloat] = [0.0]
var contentHeights2 : [CGFloat] = [0.0]
var imageHeights : [CGFloat] = [0.0]
var gt4tableview: UITableView? = nil
var indexpath: IndexPath? = nil
var delegate:ImageClickedForStoryDetails?
class MyTapGestureRecognizer: UITapGestureRecognizer {
var youTubeCode: String?
}
func configure(_ data: StoryDetailsRequest, row: IndexPath, screenSize: CGRect, gt4tableview: UITableView) {
self.gt4tableview = gt4tableview;
self.indexpath = row;
let callData = data.content[(row as NSIndexPath).row];
let url = Constants.TEMP_IMAGE_API_URL + callData.image;
// this is first webview data.
self.firstWebViewLable.frame.size.height = 1
self.firstWebViewLable.frame.size = firstWebViewLable.sizeThatFits(.zero)
let htmlString1:String! = callData.text1
self.firstWebViewLable.delegate = self;
self.firstWebViewLable.loadHTMLString(htmlString1, baseURL: nil)
// this is second webview data.
self.secondWebViewLable.frame.size.height = 1
self.secondWebViewLable.frame.size = secondWebViewLable.sizeThatFits(.zero)
let htmlString2:String! = callData.text2
self.secondWebViewLable.loadHTMLString(htmlString2, baseURL: nil)
self.secondWebViewLable.delegate = self;
if( !callData.image.isEmpty ) {
let range = url.range(of: "?", options: .backwards)?.lowerBound
var u:URL!
if(url.contains("?")) {
u = URL(string: url.substring(to: range!))
} else {
u = URL(string: url)
}
self.firstImage.image = nil
self.firstImage.kf.setImage(with: u, placeholder: nil,
options: nil, progressBlock: nil, completionHandler: { image, error, cacheType, imageURL in
if( image != nil) {
let imageW = (image?.size.width)!;
let imageheight = (image?.size.height)!;
self.firstImage.image = image;
self.firstImage.contentMode = UIViewContentMode.scaleAspectFit
self.firstImage.clipsToBounds = false
let ratio = self.firstImage.frame.size.width/imageW;
let scaledHeight = imageheight * ratio;
if(scaledHeight < imageheight)
{
//update height of your imageView frame with scaledHeight
self.firstImage.frame = CGRect(x: 0,
y: Int(self.firstWebViewLable.frame.origin.y + self.firstWebViewLable.frame.height),
width: Int(screenSize.width)-self.padding,
height: Int(scaledHeight) )
} else {
self.firstImage.frame = CGRect(x: 0,
y: Int(self.firstWebViewLable.frame.origin.y + self.firstWebViewLable.frame.height),
width: Int(screenSize.width)-self.padding,
height: Int(imageheight) )
}
} else {
self.firstImage.image = UIImage(named: "defaultimg")
}
self.secondWebViewLable.frame = CGRect(x: 0,
y: Int(self.firstImage.frame.origin.y + self.firstImage.frame.height),
width: Int(screenSize.width)-self.padding,
height: Int(self.secondWebViewLable.frame.height) )
if (self.imageHeights[0] == 0.0)
{
self.imageHeights[0] = self.firstImage.frame.height
UIView.performWithoutAnimation {
let ipath = IndexPath(item: (self.indexpath?.row)!, section: (self.indexpath?.section)!)
self.gt4tableview?.reloadRows(at: [ipath], with: UITableViewRowAnimation.none)
}
}
})
}
}
func webViewDidStartLoad(_ webView: UIWebView)
{
//myActivityIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
if(webView == self.firstWebViewLable) {
if (contentHeights1[0] != 0.0)
{
// we already know height, no need to reload cell
return
}
contentHeights1[0] = self.firstWebViewLable.scrollView.contentSize.height
UIView.performWithoutAnimation {
let ipath = IndexPath(item: (self.indexpath?.row)!, section: (self.indexpath?.section)!)
self.gt4tableview?.reloadRows(at: [ipath], with: UITableViewRowAnimation.none)
}
} else if(webView == self.secondWebViewLable) {
if (contentHeights2[0] != 0.0)
{
// we already know height, no need to reload cell
return
}
contentHeights2[0] = self.secondWebViewLable.scrollView.contentSize.height
UIView.performWithoutAnimation {
let ipath = IndexPath(item: (self.indexpath?.row)!, section: (self.indexpath?.section)!)
self.gt4tableview?.reloadRows(at: [ipath], with:UITableViewRowAnimation.none)
}
}
}
You should not calculate the cell height in cellForRow method.
and instead of heightForRowAt: use this method
TableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
and in your viewDidLoad call this.
tableView.rowHeight = UITableViewAutomaticDimension

Resources