I have a TablewView that has prototype UITableViewCell that has its own class,
Custom UITableViewCell Class
import UIKit
class H_MissingPersonTableViewCell: UITableViewCell {
#IBOutlet weak var strName: UILabel!
#IBOutlet weak var imgPerson: UIImageView!
#IBOutlet weak var Date1: UILabel!
#IBOutlet weak var Date2: UILabel!
#IBOutlet weak var MainView: UIView!
#IBOutlet weak var btnGetUpdates: UIButton!
#IBOutlet weak var btnComment: UIButton!
#IBOutlet weak var btnReadMore: 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
}
}
The TableView loads perfectly and the dataSource and delegate work fine. However, when I click a BUTTON at IndexPath.row = 0 (zero), and then I scroll down , I would see random(?) or other cells also being highlighted as a result of clicking BUTTON in row 0...
Here is my CellForRowAtIndexPath code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println("called")
var cell : CustomCell
cell = tableView.dequeueReusableCellWithIdentifier("CustomCellID", forIndexPath: indexPath) as! CustomCell
cell.strName.text = self.names[indexPath.row]
cell.imgPerson.image = UIImage(named: "\(self.persons[indexPath.row])")!
cell.btnGetUpdates.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnGetUpdates.layer.borderWidth = 1
cell.btnGetUpdates.layer.cornerRadius = 5.0
cell.btnComment.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnComment.layer.borderWidth = 1
cell.btnComment.layer.cornerRadius = 5.0
cell.btnReadMore.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnReadMore.layer.borderWidth = 1
cell.btnReadMore.layer.cornerRadius = 5.0
cell.dateMissingPersonPlace.text = self.MissingPeoplePlace[indexPath.row]
cell.dateMissingPersonSince.text = self.MissingPeopleSince[indexPath.row]
cell.btnGetUpdates.tag = indexPath.row
cell.btnGetUpdates.addTarget(self, action: "GetUpdatesButton:", forControlEvents: .TouchUpInside)
return cell
}
in my cell.btnGetUpdates , I put an action as you can see in the last part of my CellForIndex code, GetUpdatesButton:
This is the code:
func GetUpdatesButton(sender: UIButton){
println("Button Clicked \(sender.tag)")
var sen: UIButton = sender
var g : NSIndexPath = NSIndexPath(forRow: sen.tag, inSection: 0)
var t : CustomCell = self.myTableView.cellForRowAtIndexPath(g) as! CustomCell
t.btnGetUpdates.backgroundColor = UIColor.redColor()
}
The problem is, NOT ONLY the button in index 0 is being highlighted, but I would also see random buttons from other index/rows being highlighted as I scroll my tableView down.
Where did I go wrong, how can I only update the button I clicked...and not other buttons..
I have 20 items ( 20 rows) and when I clicked button in row 0, rows 3, 6, 9....are also having highlighted buttons.
ROW 0 , button clicked
ROW 3, button clicked as well, though I did not really click it.
This is occurring due to UITableview have reusablecell policy.In order to resolve this issue You need to maintain one array of selected items in cellForRowAtIndexPath method you have to verify weather this button is being hold by selected item array. if yes then apply selection styles otherwise apply normal style to it.
Check below source code for buttonclick:
func GetUpdatesButton(sender: UIButton)
{
var sen: UIButton = sender
var g : NSIndexPath = NSIndexPath(forRow: sen.tag, inSection: 0)
var t : CustomCell = self.myTableView.cellForRowAtIndexPath(g) as! CustomCell
t.btnGetUpdates.backgroundColor = UIColor.redColor()
self.selectedButtonsArray.addObject(indexpath.row)
}
Below code for applying styles on buttons in CellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : CustomCell
cell = tableView.dequeueReusableCellWithIdentifier("CustomCellID", forIndexPath: indexPath) as! CustomCell
cell.strName.text = self.names[indexPath.row]
cell.imgPerson.image = UIImage(named: "\(self.persons[indexPath.row])")!
if(self.selectedButtonsArray.containsObject(indexpath.row)){
cell.btnGetUpdates.backgroundColor = UIColor.redColor()
cell.btnGetUpdates.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnGetUpdates.layer.borderWidth = 1
cell.btnGetUpdates.layer.cornerRadius = 5.0
}else{
cell.btnGetUpdates.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnGetUpdates.layer.borderWidth = 1
cell.btnGetUpdates.layer.cornerRadius = 5.0
}
cell.btnComment.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnComment.layer.borderWidth = 1
cell.btnComment.layer.cornerRadius = 5.0
cell.btnReadMore.layer.borderColor = UIColor.darkGrayColor().CGColor
cell.btnReadMore.layer.borderWidth = 1
cell.btnReadMore.layer.cornerRadius = 5.0
cell.dateMissingPersonPlace.text = self.MissingPeoplePlace[indexPath.row]
cell.dateMissingPersonSince.text = self.MissingPeopleSince[indexPath.row]
cell.btnGetUpdates.tag = indexPath.row
cell.btnGetUpdates.addTarget(self, action: "GetUpdatesButton:",forControlEvents: .TouchUpInside)
return cell
}
I hope this helps to resolve your problem! Thanks.
Inside the GetUpdatesButton() function , keep a flag value for the indexPath.row value in a separate array. Then reload the specific cell of the table view.
Now in the cellForRowAtIndexPath function make a condition of checking the flag value is set or not, If set then change background colour else set the default colour.
PS. there are different kinds of work arounds to solve the issue. Just understand the logic and go for the one which is useful in the code.
This is because cells are being reused.
So when you colour the cells using the button action, the cell's background is being painted which i guess is working fine but the situation is that when you scroll up or down, the previous cell which is having bg colour is being reused and hence you get the previous settings it was.
A tip would be to explicitly set the background colour of the UIButton and UITableViewCell in this method func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell, as everytime it will be reused the colour will be set as default and you will NOT get the previous colour it was being reused from.
Just set
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell.backgroundColor = [UIColor whiteColor];
cell.btnGetUpdates setBackgroundColor:[UIColor whiteColor];
//with along the other code, add these two lines.
}
EDIT
for getting an effect like you want set an instance variable which stores the indexPath of the selected Cell something like an int.
In the button action method store the int to the button.tag property which is also the indexpath.row property of the cell.
in your cellForRowAtIndexPath method, do a check
if(indexpath.row == selectedIntIndexPath){
//change the colour whatever you want.
}
Finally in the IBAction Method of the button call [self.tableView reloadData]
So the complete code will be something like this
#implementation ViewController{
int selectedIntIndexPath;
}
-(IBAction)actionForButton:(id)sender{
UIButton *btn = (UIButton *)sender;
selectedIntIndexPath = btn.tag;
[self.customTableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UICustomTableViewCell *cell = (UICustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"reuseIdentifire" forIndexPath:indexPath];
if(indexPath.row == selectedIntIndexPath){
// do your colour
}
return cell;
}
Here my solutions, in order to expand #RaymondLedCarasco comment:
Tested in Swift 4 Xcode 9.3
Declare a propierty:
var numberCells: [Int] = []
When click the button of Cell:
self.numberCells.append(indexPath.row)
In CellForRowAtIndex check:
if self.numberCells.contains(indexPath.row) { ... } else { ... }
Here most of TableViewCell problems I have solved, Like when clicking the cell button after scrolling the remaining rows may be changed and when selecting at didSelectRowAt indexPath: IndexPath the row, after scrolling the remaining rows may be selected. So I created an app to solve those problems. Here adding GitHub code Find the code
In the first screen, click on a red button and just scroll down you can't see other cells are affected automatically in UITableViewCell.
Clicking on didSelectRowAt indexPath: IndexPath in the first screen you can go to details screen that's the second screen, in that screen after selecting a row other rows won't be selected automatically in UITableViewCell.
Related
I am using a tableview in an app in which I have used pagination. The request is sent to the server and it returns items in batches of size 10. everything is working fine till now. Now I have an imageview in my tableview cells (custom). I want that when the image of that imageview toggles when user taps on it. I tried this thing in the following way:
TableviewController:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell : AdventureTableViewCell = tableView.dequeueReusableCell(withIdentifier: "adventureCell" , for: indexPath) as? AdventureTableViewCell else {
fatalError("The dequeued cell is not an instance of AdventureViewCell.")
}
cell.adventureName.text = adventureList[indexPath.row]
cell.amountLabel.text = "\(adventurePriceList[indexPath.row])$"
cell.favouriteButtonHandler = {()-> Void in
if(cell.favouriteButton.image(for: .normal) == #imageLiteral(resourceName: "UnselectedFavIcon"))
{
cell.favouriteButton.setImage(#imageLiteral(resourceName: "FavSelectedBtnTabBar"), for: .normal)
}
else
{
cell.favouriteButton.setImage(#imageLiteral(resourceName: "UnselectedFavIcon"), for: .normal)
}
}
}
CustomCell:
class AdventureTableViewCell: UITableViewCell {
#IBOutlet weak var adventureName: UILabel!
#IBOutlet weak var adventureImage: UIImageView!
#IBOutlet weak var amountLabel: UILabel!
#IBOutlet weak var favouriteButton: UIButton!
#IBOutlet weak var shareButton: UIButton!
var favouriteButtonHandler:(()-> Void)!
var shareButtonHandler:(()-> Void)!
override func awakeFromNib() {
super.awakeFromNib()
adventureName.lineBreakMode = .byWordWrapping
adventureName.numberOfLines = 0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
adventureImage.af_cancelImageRequest()
adventureImage.layer.removeAllAnimations()
adventureImage.image = nil
}
#IBAction func favouriteButtonTapped(_ sender: Any) {
self.favouriteButtonHandler()
}
Now the problem which I am facing is that if user taps the first the imageview on any cell it changes its image, but along with that every 4th cell changes it image.
For example, if I have tapped imageview of first cell its image is changed but image of cell 5, 9, 13... also get changed.
What is wrong with my code? Did I miss anything? It is some problem with indexPath.row due to pagination, but i don't know what is it exactly and how to solve it. I found a similar question but its accepted solution didn't work for me, so any help would be appreciated.
if you need to toggle image and after scrolling also that should be in last toggle state means you need to use an array to store index position and toggle state by comparing index position and scroll state inside cellfoeRowAtIndex you can get the last toggle state that is one of the possible way to retain the last toggle index even when you scroll tableview otherwise you will lost your last toggle position
if self.toggleStatusArray[indexPath.row]["toggle"] as! String == "on"{
cell.favouriteButton.setImage(#imageLiteral(resourceName: "FavSelectedBtnTabBar"), for: .normal)
} else {
cell.favouriteButton.setImage(#imageLiteral(resourceName: "UnselectedFavIcon"), for: .normal)
}
cell.favouriteButtonHandler = {()-> Void in
if self.toggleStatusArray[indexPath.row]["toggle"] as! String == "on"{
//Assign Off status to particular index position in toggleStatusArray
} else {
//Assign on status to particular index position in toggleStatusArray
}
}
Hope this will help you
Your code looks OK, I see just one big error.
When u are setting dynamic data (names, images, stuff that changes all the time) use func tableView(UITableView, willDisplay: UITableViewCell, forRowAt: IndexPath) not cellForRowAt indexPath.
cellForRowAt indexPath should be used for static resources, and cell registration.
If u are on iOS 10 + take a look at prefetchDataSource gonna speed things up a loot, I love it.
https://developer.apple.com/documentation/uikit/uitableview/1771763-prefetchdatasource
Small example:
here u register the cell, and set up all the stuff that is common for all the cells in the table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "adventureCell" , for: indexPath)
cell.backgroundColor = .red
return cell
}
here adjust all the stuff that is object specific
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.nameLabel.text = model[indexPath.row].name
// also all the specific UI stuff goes here
if model[indexPath.row].age > 3 {
cell.nameLabel.textColor = .green
} else {
cell.nameLabel.textColor = .blue
}
}
You need this because cells get reused, and they have their own lifecycle, so you want to set specific data as late as possible, but you want to set the generic data as less as possible ( most of the stuff you can do once in cell init ).
Cell init is also a great place for generic data, but u can not put everything there
Also, great thing about cell willDisplay is the that u know actual size of the frame at that point
I'm just making a simple project for fun but I am having a very strange bug in my program.
This function returns 29 which is correct however it is called three times when my table view is instantiated.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
print("ingredient count: \(Sushi.ingredients.count)")
return Sushi.ingredients.count
}
And I think that (_: numberOfRowsInSection:) being called 3 times is what leads this code to execute almost three times the number of elements in the ingredients array.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath) as? IngredientCell
else
{
return UITableViewCell(style: .default, reuseIdentifier: nil)
}
cell.ingredientLabel.text = Sushi.ingredients[indexPath.row]
print("ingredient label text: \(cell.ingredientLabel.text)\nindex path: \(indexPath)\ncell index: \(cell.index)\nbutton tag: \(cell.selectButton.tag)\nindex path row: \(indexPath.row)\ncell object: \(cell)\n")
return cell
}
The table view is populated appropriately as far as it lists all the ingredients in the array correctly. However, each row of the tableView is a prototype cell that has a UILabel, a UIButton, and a UIImage. When the button is pressed the text and color change for that button but also for every thirteenth button in the tableview cells.
This class is for my individual cells
class IngredientCell: UITableViewCell
{
public var userSelected = false
public var index: Int = 0
#IBOutlet weak var picture: UIImageView!
#IBOutlet weak var selectButton: UIButton!
#IBOutlet weak var ingredientLabel: UILabel!
//This method is called when a button is pressed
#IBAction func selectIngredient(_ sender: UIButton)
{
if userSelected == false
{
userSelected = true
selectButton.setTitleColor(.red, for: .normal)
selectButton.setTitle("Remove", for: .normal)
}
else
{
userSelected = false
selectButton.setTitle("Select", for: .normal)
selectButton.setTitleColor(.blue, for: .normal)
}
}
}
I decided to debug using print statements to see if I could figure out what exactly is going on and I found that numberOfRowsInSection is called 3 times and cellForRowAtIndexPath is called a varying amount of times. I keeps iterating over the table view giving the cell objects the same memory addresses which I suppose is what causes multiple buttons to change when only one is pressed. My console output proved that different buttons in the storyboard had the same addresses in memory.
Sorry, I can only write in Objective-C. But anyway, I am just going to show you the idea.
One of the ways to update the UI contents of just a single item of a table is to reload that specific cell.
For example: Your cell contains just a button. When you press a specific button you want to change the title of that button only. Then all you have to do is to create an dictionary which references all the titles of all buttons in your table, and then set the title to that button upon reload of that specific cell.
You can do it this way:
#interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
#property NSMutableDictionary *buttonTitlesDict;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
buttonTitles = [[NSMutableDictionary alloc] init];
}
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"SimpleTableItem";
UITableViewCell *tableCell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(tableCell == nil)
{
tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
tableCell.button.title = [_buttonTitles objectForKey:#(indexPath.row)];
tableCell.button.tag = indexPath.row;
}
//reloads only a specific cell
- (IBAction)updateButton:(id)sender
{
NSInteger row = [sender tag];
[_buttonTitlesDict setObject:#"changedTitle" forKey:#(row)];
[_tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:row inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
As you can see, I just created a dictionary that holds the button title for each button with the index of the cell as the reference key. Every time I want to update the title of the button, I will get that title from the button every time the cell is loaded upon cellForRowAtIndexPath. take note that when you scroll the table, cellForRowAtIndexPath will be called when new cells appear in front of you. So as you scroll, the correct titles will be updated to the buttons.
Hope this helps.
How can I increment a value for a specific cell?
I saw this and this post. The prior I couldn't get to work (and is "brittle"?), and the former caused a segmentation fault with the functions incrementHandler() and decrementHandler().
class cell : UITableViewCell {
#IBOutlet weak var counter: UILabel
#IBAction func add (sender: AnyButton) {
counter.text = String(Int(counter.text) + 1)
// find it's corresponding stat value (from other class) and update it
stats[indexPath].counter = Int(counter.text)
}
}
class tableView: UITableViewController {
var stats = [Stat]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! ExpandedControllerCell
let stat = stats[indexPath.row]
cell.titleLabel.text = stat.name
cell.bigCounterLabel.text = String(stat.counter)
cell.smallCounterLabel.text = String(stat.counter)
return cell
}
}
In your cellForRowAtIndexPath, set a tag on the button. Then, in your IBAction method, use the tag to figure out which cell's button was tapped. Increment a value in an array, and then tell the cell at that indexPath to reload itself. (In cellForRowAtINdexPath, install the counter value into the cell.)
You can also write your button action so it uses the button's frame.origin to ask the table view which cell the button belongs to. That's better and less fragile.
See my answer in this thread for an explanation of how to do that.
I'm trying to build a custom cell with different button inside, but when I tap "follow button" in on cell and color this button it seems that other follow button get a color too...Also if I scroll up and down my tableView other button randomly get color...I'm still learning how to use custom cell...
Here there is my custom cell
class customCell: UITableViewCell
{
#IBOutlet weak var follow: UIButton!
#IBOutlet var comment: UIButton?
#IBOutlet var share: UIButton?
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellPost = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! customCell
cellPost.tag = Array(postToPrint.keys)[indexPath.row]
cellPost.follow?.tag = Array(postToPrint.keys)[indexPath.row]
cellPost.follow?.addTarget(self, action: "follow:", forControlEvents: .TouchUpInside)
return cellaPost
}
}
Here there is my function follow
func follow(sender: UIButton)
{
let postSelected = sender.tag
// In order to get indexPath from int values
let indexPath = NSIndexPath(forRow: postSelected, inSection: 1)
let cell = table.cellForRowAtIndexPath(indexPath) as! customCell
cell.follow.setTitleColor(UIColor.redColor(), forState: UIControlState)
idPostClicked = postSelected
sendHttpRequest(postClicked : idPostClicked)
}
I'm giving as tag to every cell my dictionary keys. Later I want to take cell.tag and send it as parameter in sendHttpRequest method. If I put my button function inside my customCell I want to get the cell in which there is my followButton so I can send a request with cell.tag.
However text get colored in other cell when I click only one...:/
Hmm, I feel like you are going about this in the wrong way. I would rather move the func follow into the cell itself. There's no reason for the tableView to handle this logic since it's the cell who'd like to change elements it can access on its own. Also, if you move the logic into the cell then you won't need tags or add targets etc.
class customCell: UITableViewCell
{
#IBOutlet weak var follow: UIButton!
#IBOutlet var comment: UIButton?
#IBOutlet var share: UIButton?
// Connect the follow button to this function as an action
#IBAction followPressed(sender: UIButton) {
follow.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellPost = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! customCell
return cellaPost
}
This should do the trick, I believe.
Edit
Added some missing code for UIControlState for the button. If this doesn't work could you upload a sample project? Hard to pinpoint what you are trying to do with only this piece of code.
I'm having a problem with my TableViewCell
I have two type of cell in my storyboard.
when i scroll, the text overlaps in some cells. I Try everything but I do not know how else to do. thank you very much for the help
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var storeNew = systemsBlog.getStore(listNews[indexPath.row].getIdStore())
var newNotice = listNews[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCell", forIndexPath: indexPath) as? TimelineCell
cell!.nameLabel.text = storeNew.getName()
cell!.postLabel?.text = newNotice.getText()
cell!.postLabel?.numberOfLines = 0
cell!.dateLabel.text = newNotice.getDate()
cell!.typeImageView?.tag = indexPath.row;
return cell!
}
class TimelineCell : UITableViewCell {
#IBOutlet var nameLabel : UILabel!
#IBOutlet var postLabel : UILabel?
#IBOutlet var dateLabel : UILabel!
override func awakeFromNib() {
postLabel?.font = UIFont(name: "Roboto-Thin", size: 14)
}
override func layoutSubviews() {
super.layoutSubviews()
}
I can fix the problem. In the storyboard, the label have unchacked "Clears Graphics Context". I checked and for now it solved! Thanks for the help!
I had a similar issue with one of my UITableViews in the past. There are a bunch of things that could cause this, but maybe it is the same thing that happened to me.
I see that you are using a custom tableViewCell. What could be happening is when you set the text of the cell, it adds a label view with that text. Now say you scroll through the tableview and that cell disappears. If you were to reuse that cell and you did not remove the label from the subview, or set the text of that label again to the desired text, you will be reusing the tableviewcell with a previous label on it and adding a new label with new text to it, overlapping the text.
My suggestion would be to make sure you do not keep adding UIlabels as subviews in the TimelineCell class unless no label exists. if a label exists edit the text of that label not of the cell.
As per apple documentation:
The table view’s data source implementation of
tableView:cellForRowAtIndexPath: should always reset all content when
reusing a cell.
It seems that your problem is that you not always setting postLabel, causing it to write on top of the other cells, try this:
//reuse postLabel and set to blank it no value is returned by the function
let cell = tableView.dequeueReusableCellWithIdentifier("TimelineCell", forIndexPath: indexPath) as? TimelineCell
cell!.nameLabel.text = storeNew.getName()
if newNotice.getText() != nil{
cell!.postLabel.text = newNotice.getText()
} else {cell!.postLabel.text = ''}
cell!.postLabel.numberOfLines = 0
cell!.dateLabel.text = newNotice.getDate()
cell!.typeImageView?.tag = indexPath.row;
return cell!
}
//Make postLabel mandatory and set the font details in the xcode
class TimelineCell : UITableViewCell {
#IBOutlet var nameLabel : UILabel!
#IBOutlet var postLabel : UILabel!
#IBOutlet var dateLabel : UILabel!
override func awakeFromNib() {
//set this in xcode
}
override func layoutSubviews() {
super.layoutSubviews()
}
Also be sure that you are not creating any UI element and appending to the cell, as if you are you need to dispose it before you recycle the cell.
You can try setting:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0 // Set this value as a good estimation according to your cells
}
In the View Controller containing your tableView.
Make sure the layout constraints in your TimelineCell define a clear line of height constraints
Another option is responding to:
tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0 // Your height depending on the indexPath
}
Always in the ViewController that contains your tableView and, I assume, is the tableView's UITableViewDelegate
Hope this helps
Set cell to nil that will fix some error.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? ImageCellTableViewCell
cell = nil
if cell == nil {
cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath) as? ImageCellTableViewCell
}
cell.yourcoustomtextTextLabel.text = "this is text"
cell.yourcoustomtextImageView.image = image
return cell
}