Centering Image In UITableView - ios

I am having a lot of problems centering an image in my UITableViewCell. I have spent countless hours trying all the solutions listed on stack overflow as well as countless other websites. My text will center, but for some reason my image won't center and there is a white line on the left side of the table that I can not get rid of either.(From what I have read in the iOS documentation, this is new in iOS 7, but people have gotten it to go away) I have set all the insets to zero both programmatically and via the inspector. I am using core data to retrieve the images, which is working fine, it is just my image won't center.
Here is my method for the tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSManagedObject *moment = [self.moments objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [moment valueForKey:#"name"]];
UIImage *cellImage = [UIImage imageWithData:[moment valueForKey:#"image"]];
cell.imageView.image = cellImage;
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.textColor = [UIColor whiteColor];
return cell;
}
Along with that, I can't seem to get my label to go above the image, which is a whole other problem. But what I have done to try to fix this is make a custom cell subclass, which didn't work. I am all out of resources and ideas to fix this.
EDIT ABOUT CUSTOM SUBCLASS
So I might have the wrong idea of a custom subclass of UITableViewCell. But what I did was create a class, with two variables, one for the UIImageView and the other for the label, in a class called customCell. Then in the main table view I called them like this:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSManagedObject *moment = [self.moments objectAtIndex:indexPath.row];
//cell.textLabel.text = [NSString stringWithFormat:#"%#", [moment valueForKey:#"name"]];
//UIImage *cellImage = [UIImage imageWithData:[moment valueForKey:#"image"]];
//cell.imageView.image = cellImage;
//cell.textLabel.textAlignment = NSTextAlignmentCenter;
//cell.textLabel.textColor = [UIColor whiteColor];
CustomCell *customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[customCell.cellTitle setText:[NSString stringWithFormat:#"%#", [moment valueForKey:#"name"]]];
[customCell.cellImage setImage:[UIImage imageWithData:[moment valueForKey:#"image"]]];
return cell;
}
Then simply in the custom cell class I just connected the label and image to an IBOutlet and synthesized them.
EDIT 2 CUSTOM SUBCLASS ADDITION
The header file has two properties. One for cellTitle which is a UILabel and one for cellImage which is a UIImageView.
#interface CustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *cellImage;
#property (weak, nonatomic) IBOutlet UILabel *cellTitle;
The implementation file:
Here I am just synthesizing the two objects.
#synthesize cellImage;
#synthesize cellTitle;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}

CustomCell *customCell = (CustomCell *)[tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
[customCell.cellTitle setText:[NSString stringWithFormat:#"%#",
[moment valueForKey:#"name"]]];
[customCell.cellImage setImage:
[UIImage imageWithData:[moment valueForKey:#"image"]]];
return cell;
I believe you're returning the default cell, not the customCell

To your cell subclass make a method
- (void)layoutSubviews {
self.cellTitle.frame = CGRectMake(...); //self.view.frame will return the cell's frame
self.cellImage.frame = CGRectMake(...); //you should set the frames of title and imageView however you want them in here
}

(void)layoutSubviews {
[Self.cellImage setCentre:Self.contentView.Centre];}

After a long day of trying to figure this out, I had one little mistake that caused this whole debacle. I had my cell Identifier set to "CellIdentifier" in the inspector. I changed it to "Cell" and edited some code and boom!
I added some code to the CustomCell:
-(void)layoutSubviews {
self.imageView.center = self.contentView.center;
[super layoutSubviews];
}
Which fixed everything. No more bar on the right side and both title and image are centered. Here is the final code in the TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
//CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSManagedObject *moment = [self.moments objectAtIndex:indexPath.row];
/*cell.textLabel.text = [NSString stringWithFormat:#"%#", [moment valueForKey:#"name"]];
UIImage *cellImage = [UIImage imageWithData:[moment valueForKey:#"image"]];
cell.imageView.image = cellImage;
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.textColor = [UIColor whiteColor];*/
[cell.cellImage setImage:[UIImage imageWithData:[moment valueForKey:#"image"]]];
[cell.cellTitle setText:[NSString stringWithFormat:#"%#", [moment valueForKey:#"name"]]];
return cell;
}
I still have commented out code in there, sorry about that. But thank you to all whole helped out in solving this problem!

DONT USE THE DEFAULT IMAGEVIEW FROM THE CELL... create a UIImageView... add it to cell's view at the desired position.. =)
GL HF

you can make custom cell for table view and load this cell in table view as you can place your contents in custom cell at desired position whatever you want.This is the best approach to make table view cell if your application requires complex design in table view.Example:static NSString *CustomCellIdentifier = #"CEll";//[NSString stringWithFormat:#"Cell%d",indexPath.row];
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier]; implement this in your cellforrowAtIndexPath method and add your cell nib -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
self = (customCell *)[[[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil] firstObject];}
}

Related

Bug with UITableViewCell ios

I'm working on an iOS project .I created an UITableView to display a list of drones . Everything works fine but I noticed that there is a bug when I click on the cell to display the details of the drone . As u can see in the images below.
When the tableView get loded
When clicked on cell
and this my code when I select a cell :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *_storyboardName = #"Main";
UIStoryboard *_storyboard = [UIStoryboard storyboardWithName:_storyboardName bundle: nil];
DroneDetailsViewController *detailsVC = [_storyboard instantiateViewControllerWithIdentifier:#"DroneDetailsViewController"];
detailsVC.droneObj = [drones objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailsVC animated:YES];
[detailsVC.navigationController setNavigationBarHidden:NO animated:YES];
}
This my code for cellForRowAtIndexPath :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"drone";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
DroneObject *droneObjDisplay = nil;
droneObjDisplay = [drones objectAtIndex:indexPath.row];
NSData *data = [[NSData alloc]initWithBase64EncodedString:droneObjDisplay.modelMSide options:NSDataBase64DecodingIgnoreUnknownCharacters];
[self initCellWithComponents:cell :data :droneObjDisplay.modelName :droneObjDisplay.modelNumber];
return cell;
}
and this the initCelWithComponents :
- (void)initCellWithComponents :(UITableViewCell *)cell :(NSData *)dataImage :(NSString *)title :(NSString *)subTitle {
UIView *viewCell = [[UIView alloc] initWithFrame:CGRectMake(VIEW_MARGIN, VIEW_MARGIN, widthtScreen-20, VIEW_IMAGE_HEIGHT)];
viewCell.layer.borderColor = [UIColor colorWithHexString:NSLocalizedString(#"border_color", nil)].CGColor;
viewCell.backgroundColor = [UIColor whiteColor];
viewCell.layer.borderWidth = 0.5f;
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(VIEW_MARGIN,VIEW_MARGIN, VIEW_IMAGE_HEIGHT-(2*VIEW_MARGIN),VIEW_IMAGE_HEIGHT-(2*VIEW_MARGIN))];
image.image=[UIImage imageWithData:dataImage];
[viewCell addSubview:image];
UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(image.frame.size.width+2*VIEW_MARGIN, VIEW_MARGIN, viewCell.frame.size.width-(VIEW_IMAGE_HEIGHT-(4*VIEW_MARGIN)), 21)];
titleLabel.text = title;
titleLabel.textColor = [UIColor blackColor];
[titleLabel setFont:[UIFont systemFontOfSize:15]];
[viewCell addSubview:titleLabel];
UILabel *subTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(image.frame.size.width+2*VIEW_MARGIN, 3*VIEW_MARGIN, viewCell.frame.size.width-(VIEW_IMAGE_HEIGHT-(4*VIEW_MARGIN)), 21)];
subTitleLabel.text = subTitle;
subTitleLabel.textColor = [UIColor blackColor];
[subTitleLabel setFont:[UIFont systemFontOfSize:13]];
[viewCell addSubview:subTitleLabel];
cell.contentView.backgroundColor = [UIColor colorWithHexString:NSLocalizedString(#"gray_background", nil)];
[cell.contentView addSubview:viewCell];
}
any ideas how to fix that ?!
Your cell's style is UITableViewCellStyleSubtitle and you also adding title and subtitle label manually also.
If you are using cell's style as UITableViewCellStyleSubtitle then you can directly use
cell.textLabel.text = #"your title label's text";
cell.detailTextLabel.text = #"your detail label's text";
If you will add another label then it will creates duplicate!!!!
Since you are initialising UIView and UILabel in method inside cellForRowAtIndexPath and adding them as subview, these controls are being added to your cell each time cell is reloaded. Below code identifies each cell with a unique identifier and loads the cell only if that particular cell is not available in UITableView.
I have written droneObjDisplay.droneId to uniquely identify cell, you can write anything for droneObjDisplay.__ that is unique identifier of your object.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
DroneObject *droneObjDisplay = nil;
droneObjDisplay = [drones objectAtIndex:indexPath.row];
NSString *CellIdentifier = [NSString stringWithFormat:#"drone_%d", droneObjDisplay.droneId];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSData *data = [[NSData alloc]initWithBase64EncodedString:droneObjDisplay.modelMSide options:NSDataBase64DecodingIgnoreUnknownCharacters];
[self initCellWithComponents:cell :data :droneObjDisplay.modelName :droneObjDisplay.modelNumber];
}
return cell;
}
Hope it helps.
The TableViewCell could be designed and used by either one of the following ways,
If you are using the storyboard then you can simply design the prototype cell on the TableView on storyboard itself and then giving an identifier to the cell. If you are using this way then add the component on the storyboard only and give tag to each component to access it in the code if you are not subclassing the UITableViewCell, and dequeue the cell as below,
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
UILabel *labelValue = (UILabel*) [cell viewWithTag:10];
Design the TableViewCell on the storyboard as you did in 1 way and then simply create a subclass of UITableViewCell class and set that class as a Custom Class of the cell by selecting the cell on storyboard, this way you can create the outlet of each component in the cell and you do not need to access the component by the tags. Below is the code to dequeue the cell,
CellSubClassed *cell = (CellSubClassed*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.labelXYZ.text = arrayDataSource[indexPath.row][#"key"];
This is the old way before storyboard was introduced, Create subclass of UITableView cell and create a xib file with the same name you give to UiTableViewCell subclass, create the outlets of component you want to access. Below is the code to dequeue cell,
NSArray *nib;
static NSString *strNibName = #"CustomCell";
nib = [[NSBundle mainBundle] loadNibNamed:strNibName owner:self options:nil];
CustomCell *cell = [nib objectAtIndex:0];
cell.imageView.image = arrayDataSource[indexPath.row];
The last way is using TableView's default cells, just create the tableView on storyboard/xib and dequeue the cell as below,
static NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = #"xyz";
The default tableView cell styles are,
UITableViewCellStyleDefault
UITableViewCellStyleSubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
You can read about more on Apple Developer docs here.
So in your case you are mixing the two ways of dequeuing the cell, if you want to add the component manually as you did and you don't want to design the component on the storyboard or Xib then you just create the subclass of UITableView cell and then create the component in the awakeFromNib method and dequeue the cell as explained in 3 way.
Hope it helps you.
Ok finally, after getting your answers guys , I created a Custom Cell a subclass of UITableViewCell and I added all my components there . The main problem was how I will call it without UI (storyboard or xib ) just by code .
So after the creation of the custom cell I added this line to my viewdidload :
[self.tableView registerClass:[CustomCellTableViewCell class] forCellReuseIdentifier:#"CustomCellTableViewCell"];
then in the cellForRowAtIndexPath I just added the custom cell :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
DroneObject *droneObjDisplay = nil;
droneObjDisplay = [drones objectAtIndex:indexPath.row];
static NSString *identifier = #"CustomCellTableViewCell";
CustomCellTableViewCell *cell = (CustomCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
NSData *data = [[NSData alloc]initWithBase64EncodedString:droneObjDisplay.modelMSide options:NSDataBase64DecodingIgnoreUnknownCharacters];
cell.image.image = [UIImage imageWithData:data];
cell.titleLabel.text = droneObjDisplay.modelName;
cell.subTitleLabel.text = droneObjDisplay.modelNumber;
return cell;
}

ios/xcode:How to Add Accessory View to Custom Cell

I am following a tutorial that uses a custom cell created in Storyboard in a tableview and then adds an accessory view. The table is loading okay. However when I try to add an accessory view (an image), nothing appears. Could there be some setting in storyboard that is wrong? A problem in the code? Or why is the accessory view not appearing
Here is the method where the tutorial says to add the accessory view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
IDContactImport *contactImport = self.contacts[indexPath.row];
IDTableViewCell *idTableCell =(IDTableViewCell *)cell;
idTableCell.contactImport=contactImport;
if (contactImport.imageData==nil)
{
idTableCell.iconView.image = [UIImage imageNamed:#"headshot.jpg"];
}
else{
idTableCell.iconView.image = [UIImage imageWithData:contactImport.imageData];
}
//HERE IS ACCESSORY VIEW
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"checkbox.jpg"]];
idTableCell.accessoryView = imageView;
// [self updateAccessoryForTableCell:cell atIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
return cell;
}
Thanks for any suggestions
static NSString *cellIdentifier = #"CELLIDENTIFIER";
UITableViewCell *customCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
UIImageView *sampleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sampleImage.png"]];
[customCell setAccessoryView:sampleImage];
Hope it useful for you.!!!
It should work. Please try blow code. there is no issue on Storyboard.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"customCell";
CustomCellView *cell = [ctableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
long row = [indexPath row];
cell.name.text = carname[row];
cell.model.text = carModel[row];
cell.carImg.image = [UIImage imageNamed:carImage[row]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SelectedStar_green.png"]];
cell.accessoryView = imageView;
// Configure the cell...
return cell;
}
Change the dequeueReusableCellWithIdentifier: call to:
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
This will always returns a cell, so you will never have to check for nil.
// if (cell == nil) {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
I don't think any of the above answers have addressed your issue. You are right by mentioning that it all has to do with your storyboard.
In order to fix this, go into your Main.storyboard, click on the table view and reset the view to suggested constraints following the below picture.

Collapsable Cell

I have a UITableView with two different custom table cells. The first cell appears normal after I start the app. The second cell will appear when you click on them.
Can anybody help me or has an idea?
Thanks a lot.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *MyIdentifier = #"customCell2";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if(cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor grayColor];
cell.textLabel.font = [UIFont fontWithName:#"STHeitiSC-Light" size:9.0];
}
return cell;
}
Having done custom UITableViewCell in the past I usually handle the nib loading in the custom class itself.
The basic header for the custom cell.
#interface RequestsTableViewCell : UITableViewCell {
// Ivars.
}
// Properties.
- (id) initWithRequestModel: (RequestModel *) model style:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier forQueryType:(int) requestType;
// Other methods, etc.
#end
The custom cell with a designated initializer.
#implementation RequestsTableViewCell
- (id) initWithRequestModel: (RequestModel *) model style:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier forQueryType:(int) requestType {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"RequestsTableViewCell" owner:self options:nil];
self = [nibArray objectAtIndex:0];
requestModel = model;
queryType = requestType;
[self setRequestThumbnail];
[self setRequestCategory];
[self setRequestAddress];
[self setRequestStatusDate];
[self setRequestStatus];
[self setRequestFollowed];
[self setRequestComment];
[self setAppearance];
}
return self;
}
There would also be a custom xib for the custom UITableViewCell that corresponds and has the custom class set in the identity inspector.
In the UITableViewController.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"Cell Id";
RequestModel *request = nil;
// Other code for search, etc
request = [self.serviceRequests objectAtIndex:indexPath.row];
RequestsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if(!cell) {
cell = [[RequestsTableViewCell alloc] initWithRequestModel:request style:UITableViewCellStyleDefault reuseIdentifier:cellId forQueryType:queryTypeIndicator];
}
return cell;
}
It also sounds like you have more than one custom cell type in your question? Can you elaborate on how it is all supposed to function? You say that you have to click one cell to make another appear, can you explain that interaction?
I did something similar, but made the cell 'expand', instead of adding a new cell. Of course then you don't have two cells, but you can resize your one cell, add subframes,...
You can keep a boolean in your UITableViewCell object (BOOL cellIsExpanded), and set that on tap gesture. Then in drawRect of the TableViewCell, layout your cell accordingly.
Example code, on expand, make cell height 20-->80 and add a UIButton:
In the TableViewController, overload heightForRowAtIndexPath (this will resize your cell if 'expanded'):
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
YourEntity *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
if (!record.cellIsExpanded)
return 20.; // cell is smaller if collapsed
else
return 80.; // bigger cell
}
In the TableViewCell, add or remove subframes:
#interface MyTableViewCell ()
#property(nonatomic) BOOL cellIsExpanded
#property(strong, nonatomic) UITextField *myTextField;
#property(strong, nonatomic) UIButton *clickMeButton;
#end
#implementation MyTableViewCell
- (void)drawRect:(CGRect)rect {
if(!self.cellIsExpanded){
// layout your collapsed cell, for example:
self.myTextField = [[UITextField alloc] initWithFrame:self.frame];
self.myTextField.text = #"Collapsed cell";
// remove button, only present in expanded view :
self.clickMeButton=nil;
}
else{
self.myTextField.text = #"Expanded cell";
// add button below textfield
self.clickMeButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 10, 10)];
}
}
#end

UILabel Not Showing On Static TableView

Hello I'm having a little bit of trouble with something I'm working on. I have a static TableView with sections and I'm trying to get my text to be positioned in a certain spot so I have a ui label linked to a uitableviewcell. But for some reason It's not working. If you have any ideas on why I'm having trouble with this that would be great. I'm also a bit new to iOS development, just putting that out there.
TableViewController.m:
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[TableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int row = [indexPath row];
if (indexPath.section==0)
cell.textLabel.text = _1[row];
if (indexPath.section==1)
cell.textLabel.text = _2[row];
if (indexPath.section==2)
cell.textLabel.text = _3[row];
if (indexPath.section==3)
cell.textLabel.text = _4[row];
if (indexPath.section==4)
cell.textLabel.text = _5[row];
if (indexPath.section==5)
cell.textLabel.text = _6[row];
if (indexPath.section==6)
cell.textLabel.text = _7[row];
if (indexPath.section==7)
cell.textLabel.text = _8[row];
return cell;
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
#end
TableCell.h:
#import <UIKit/UIKit.h>
#interface TableCell : UITableViewCell
#property (strong,nonatomic) IBOutlet UILabel *TitleLabel;
#end
replace this line
cell.textLabel.text = _1[row];
with
cell.TitleLabel.text = _1[row];
this line is not needed anymore
if (cell == nil) {
cell = [[TableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
in case TableCell is with xib, then you need to load it.
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"TableCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
cell.TitleLabel.text = _1[row];
return cell;
you should check this
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier
method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically. if you previously registered a class or nib file with the same reuse identifier, the class you specify in the cellClass parameter replaces the old entry (Apple Document)
in your viewDidLoad method
[self.tableView registerClass:[TableCell class]
forCellReuseIdentifier:#"CellIdentifier"];

iOS: UITableView mixes up data when scrolling too fast

I've subclassed the UITableViewCell to add custom appearance to it. At the init level of the MYTableViewCell I added 4 subviews: UIImageView, and three UILabel(s). All 4 subviews have a different Tag assigned to them.
Inside the cellForRowAtIndexPath method I either create a new cell if it wasn't available at first, or reuse available one and assign the proper text to the ui labels.
The problem I am having is that if I try to scroll super fast, then the data gets messed up, however if I scroll up and down more slowly, then everything works fine.
Any thoughts??
Below is the code:
- (MyTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"itemListTableViewCell";
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
DisplayableEntity *displayableEntity = [self.fetchedResultsController objectAtIndexPath:indexPath];
if( ! cell ) {
cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[self tableView:tableView appearanceForCell:cell withEntity:displayableEntity];
} else {
UIImageView *imageView = (UIImageView *) [cell viewWithTag:IMAGEVIEW_TAG];
imageView.image = [UIImage imageNamed:displayableEntity.displayImageName];
UILabel *titleLabel = (UILabel *) [cell viewWithTag:TITLEVIEW_TAG];
titleLabel.text = displayableEntity.entityName;
UILabel *itemDescription = (UILabel *) [cell viewWithTag:DESCRIPTION_TAG];
itemDescription.text = displayableEntity.entityDesctiption;
}
}
// some code removed to make it brief
- (void)tableView:(UITableView *)tableView appearanceForCell:(MyTableViewCell *)cell withEntity:(DisplayableEntity *)entity {
// cell image view
UIImageView *cellImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[entity displayImageName]]];
[cellImageView setTag:IMAGEVIEW_TAG];
[cell addSubview:cellImageView];
// adding entity name label
UILabel *itemTitleName = [self itemTitleNameLabelWithFrame:itemNameLabelRect itemName:[entity entityName]];
[itemTitleName setTag:TITLEVIEW_TAG];
[cell addSubview:itemTitleName];
// adding 'assigned to' label right under the item name label
UILabel *itemDescriptionLabel = [self itemDescriptionLabelWithFrame:descriptionLabelFrame itemDescription:[entity entityDesctiption]];
[itemDescriptionLabel setTag:DESCRIPTION_TAG];
[cell addSubview:itemDescriptionLabel];
}
I see some troubles in tableView:cellForRowAtIndexPath: logic
It should be:
Dequeue cell
If cell cannot be dequeued - create the new one
Set all cell properties
I mean something like this:
- (MyTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"itemListTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
} // <-- Note there is no else, we should reset properties in both cases
NSManagedObject *managedObject = [_fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [managedObject valueForKey:#"text"];
cell.imageView.image = [managedObject valueForKey:#"image"];
return cell;
}

Resources