How to set same Size images in Table View? - iphone

I am new to iPhone
I am creating an application which display the name of countries and Theirs flag as a thumbnail., The problem is the size of all all images are not same so there is unpredictable output.
Code Is Given Below
.h file
IBOutlet UILabel *countryLabel;
IBOutlet UIImageView *thumbnailView;
IBOutlet UILabel *populationLable;
.m File
#import "TextFieldAlertViewController.h"
#implementation TextFieldAlertViewController
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
return cell;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)loadView {
}
- (void)viewDidLoad {
[super viewDidLoad];
tableData = [NSArray arrayWithObjects:#"Australia", #"Brazil",#"China", #"Denmark", #"England", #"France", #"Germany", #"Hong Kong", #"India", #"Japan", #"Korea", #"Labanon", #"Malasiya", #"Niegiria", #"Peru", #"Swidden", nil];
thumbnails = [NSArrayarrayWithObjects:#"aus.png",#"br.png",#"ch.png",#"dk.png",#"eng.png",#"fr.png", #"ger.png",#"hk.png",#"in.png",#"jp.png",#"ko.png",#"lb.png",#"my.png",#"ng.png",#"pe.png",#"sw.png",nil];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
#end

just set Frame of your cell imageView in cellForRowAtIndexPart section
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier];
}
cell.imageView.frame = CGRectMake(50, 10, 200, 50);
return cell;
}

try this line just above "return cell;":
cell.imageView.frame = CGRectMake(0,0,32,32);

I actually have the same problem right now, the current answers will not work because all of the standard views in a UITableViewCell are resized in the layoutSubviews method, so changing the frame of the view, at least in the tableView:cellForRowAtIndexPath: will not work.
As far as I know you have the following options:
Change the frame of the imageView by subclassing the UITableViewCell in the layoutSubviews after the [super layoutSubviews] call, I have tried this and you have to also move the textLabel because it will be positioned in the wrong place since the image is now bigger/smaller.
Don't use the imageView, rather create your own UIImageView, of course you will have to reposition the textLabel or rather create your own UILabel, the downside is that you have to be aware of the placement and size of your UIImageView and UILabel when the device is rotated, tableView is resized, etc.
Pad your images with transparency so all are the same size and be able to take advantage of the default UITableViewCell automatic layout
Resize your images on the spot, like in this answer: Incorrect size of Images in TableView
I think I'll use the third option for my own case, since I am in control of the images used in each cell.

Related

How to get selected image and navigate to detail view from UITableViewCell (Custom cell) load by nib in UITableView

I have an UITableViewCell and in this cell i have 3 UIImageView.This is my custom cell loaded in my UITableView by nib file.I want to get selected image when i tapped on image and navigate in detailViewController. for that i added UIGestureRecognizer in all 3 ImageView at the time of creating cell.
This is my demo application because I'm new in iphone developing
and my application is like photo gallary when tap on photo navigate the page and display that photo in big size.
i have to use UItableView and custom cell so please don't give other suggestions because i'm in training and i have to use this without it i already done.
but in UITableView when i tap on image the whole cell is select and my method given on #selecter is not call.
Code:-
MasterViewController.m file
#implementation MasterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Gallery", #"Gallery");
}
return self;
}
- (void)viewDidLoad
{
NSLog(#"Enter in viewDidLoad method");
//alloc init array with array of .png and .jpg file names.
imgFileName = [[NSArray alloc]initWithArray:[[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle]bundlePath] error:nil]filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH[cd] '.png'","self ENDSWITH[cd] '.jpg'"]]];
NSLog(#"Image file name = %#",imgFileName);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
NSLog(#"Enter in viewDidLoad method");
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return imgFileName.count/3+1;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Enter Cell creating process.....");
// Similar to UITableViewCell, but
static NSString *CellIdentifier = #"Cell";
Customcell *cell = (Customcell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:#"Customcell" owner:self options:nil];
for (id currentobject in topLevelObject)
{
if ([currentobject isKindOfClass:[UITableViewCell class]])
{
NSLog(#"Enter in IF for Creating cell");
cell = (Customcell *) currentobject;
NSLog(#"cell reuseIdentifier = %#",cell.reuseIdentifier);
break;
}
}
}
NSLog(#"Row == %d",indexPath.row);
if ((indexPath.row*3) == imgFileName.count)
{
NSLog(#"Counter in 1st if == %d ",(indexPath.row*3));
return NULL;
}
NSLog(#"Counter out 1st if == %d ",(indexPath.row*3));
[cell.img1 setImage:[UIImage imageNamed:[imgFileName objectAtIndex:(indexPath.row*3)]]];
[cell.img1 setTag:indexPath.row*3];
[cell.img1 addGestureRecognizer:[[UIGestureRecognizer alloc]initWithTarget:self action:#selector(imageTapped:)]];
if (((indexPath.row*3)+1) == imgFileName.count)
{
NSLog(#"Counter in 2nd if == %d ",(indexPath.row*3)+1);
return cell;
}
NSLog(#"Counter out 2nd if == %d ",(indexPath.row*3)+1);
[cell.img2 setImage:[UIImage imageNamed:[imgFileName objectAtIndex:(indexPath.row*3)+1]]];
[cell.img2 setTag:(indexPath.row*3)+1];
[cell.img2 addGestureRecognizer:[[UIGestureRecognizer alloc]initWithTarget:self action:#selector(imageTapped:)]];
if (((indexPath.row*3)+2) == imgFileName.count)
{
NSLog(#"Counter in 3rd if == %d ",(indexPath.row*3)+2);
return cell;
}
NSLog(#"Counter out 3rd if == %d ",(indexPath.row*3)+2);
[cell.img3 setImage:[UIImage imageNamed:[imgFileName objectAtIndex:(indexPath.row*3)+2]]];
[cell.img3 setTag:(indexPath.row)+2];
[cell.img3 addGestureRecognizer:[[UIGestureRecognizer alloc]initWithTarget:self action:#selector(imageTapped:)]];
NSLog(#"Exit cell creating process...");
return cell;
}
-(void)imageTapped:(UITapGestureRecognizer *)sender
{
NSLog(#"Enter in imageTapped method");
DetailViewController *detailViewController = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
UIImageView *img = (UIImageView *)sender.view;//cast sender obj. to ImageView
NSLog(#"The Selected tag is = %d",img.tag);
detailViewController.imageD = img.image;
[img release];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
NSLog(#"Exit from imageTapped method");
}
CustomCell.m file
#import "Customcell.h"
#interface Customcell ()
#end
#implementation Customcell
#synthesize img1,img2,img3;
#end
DetailViewController.m file
- (void)viewDidLoad
{
imageViewD = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, imageD.size.width,imageD.size.height)];
[imageViewD setImage:imageD];
//[self.view addSubview:imageViewD];
[super viewDidLoad];
UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
if (imageViewD.frame.size.height > self.view.frame.size.height)
{
scroll.contentSize = CGSizeMake(imageViewD.frame.size.width+50, imageViewD.frame.size.height+50);
}
[scroll addSubview:imageViewD];
[self.view addSubview:scroll];
}
i hope this code will help you and you can give me answer or suggestion quickly.
I think the issue is because you havent specified what type of gesture is to be applied, there are different types of gestures
Please try this
UITapGestureRecognizer *tapped=[[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(imageTapped:)];
[cell.img1 addGestureRecognizer:tapped];
Similarly add UITapGestureRecognizer for all the other 2 imageviews

How to add a custom view on selected cell

I want to add a view on selected cell of tableview. I'm writing this code.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor=[UIColor greenColor];
myView.tag=1001;
[cell.contentView addSubview:myView];
}
after writing this code my other cells are not showing due to this view. I want to increase selected cell's height to 200 and add my custom view on selected cell.
can anyone tell me how to do this,,
thanks in advance.
Create a property of the selected cell
#property (nonatomic) int currentSelection;
Then initialize it here
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.currentSelection = -1;
}
In heightForRowAtIndexPath you can set the height you want for the selected cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
int rowHeight;
if ([indexPath row] == self.currentSelection) {
rowHeight = 200;
}
else
rowHeight = CURRENT_HEIGHT_HERE;
return rowHeight;
}
Then add you view here and hide it as:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor=[UIColor greenColor];
myView.tag=1001;
[myView setHidden:YES];
[cell.contentView addSubview:myView];
// Configure the cell.
return cell;
}
In didSelectRow you save the current selection and save a dynamic height, if required
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// do things with your cell here
// set selection
self.currentSelection = indexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[[cell viewWithTag:1001] setHidden:NO];
// animate
[tableView beginUpdates];
[tableView endUpdates];
}
ok as i told u better u need to subclass the UITableViewCell in the following example, when selecting the cell it will add custom view to selected cell better u go through this and change it according to your requirement . Hope this helps u :)
//in subclassed cell "CustomCell.h" file
#interface CustomCell : UITableViewCell
{
UIView *aView; //to hold ur view
BOOL addView; //to check wheather to add view or not
}
#property(nonatomic, retain) UIView *aView;
#property(nonatomic, assign) BOOL addView;
#end
//in "CustomCell.m" file
#import "CustomCell.h"
#implementation CustomCell
#synthesize aView;
#synthesize addView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
aView = [[UIView alloc]initWithFrame:CGRectZero]; //init the view with zero rect as if u want initially frame is zero
aView.backgroundColor = [UIColor greenColor]; //to know weather it is added or not
[self addSubview:aView];//added to cell
}
return self;
}
- (void)dealloc
{
[aView release];
[super dealloc];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews
{
[super layoutSubviews];
if(self.addView) //if the view is added
{
self.aView.frame = CGRectMake(10, 3, 100,200);
}
else
{
self.aView.frame = CGRectZero;//if there is no view
}
}
//in your ViewController.h file
#interface ViewController : UIViewController<CountdownTimerDelegate>
#property (retain, nonatomic) IBOutlet UITableView *aTableView;
#property (nonatomic, retain) NSIndexPath *selectedIndexPath;
#end
//in ViewController.m file
#import"CustomCell" //add this to header file
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [self.aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell =[[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(self.selectedIndexPath != nil)
{
if(self.selectedIndexPath.row == indexPath.row)
cell.addView = YES;
else
cell.addView = NO;
}
//initially set it no for all cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//in did select row at indexpath
self.selectedIndexPath = indexPath;
[self.aTableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.selectedIndexPath != nil)
{
if(self.selectedIndexPath.row == indexPath.row)
{
return 200;
}
return 45;
}
else
return 45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
selectedIndex = indexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
myView.backgroundColor = [UIColor greenColor];
myView.tag = 1001;
[cell.contentView addSubview:myView];
[tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if ([indexPath row] == selectedIndex) {
return myView.bound.size.height;
}
else
return currentHeight;
}
Hope this will work.

how to add 2 object into a tableview cell

New to objective. I am trying to put 2 values into a table view. this is part of the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.font = [UIFont systemFontOfSize:14]; //Change this value to adjust size
cell.textLabel.numberOfLines = 2;
NSString *desc= #"Alight Destination =";
cell.textLabel.text = desc,[alDescArray objectAtIndex:indexPath.row];
return cell;
}
for this line cell.textLabel.text = desc,[alDescArray objectAtIndex:indexPath.row];
the table only display Alight Destination = without adding in the values for [alDescArray objectAtIndex:indexPath.row];
What part did i do wrongly pls help
You should use
cell.textLabel.text=[NSString stringWithFormate:#"%# %#",desc,[alDescArray objectAtIndex:indexPath.row];
or
NSString *desc=[NSString stringWithFormart: #"Alight Destination = %#",[alDescArray objectAtIndex:indexPath.row] ];
cell.textLabel.text = desc;
`
Use following way...
cell.textLabel.text = [NSString stringWithFormat:#"%# %#",desc,[alDescArray objectAtIndex:indexPath.row]];
I think it will be helpful to you.
guess subclassing UITableViewCell will be useful. find code below hope it will help..!
# INTERFACE FILE
#import <UIKit/UIKit.h>
#interface CustomTableViewCell : UITableViewCell {
UIImageView *imageView;
UILabel *titleLabel1;
UILabel *titleLabel2;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
- (void)setValuesForCell:(YourModal*)agent withIndexPath:(NSIndexPath*)indexPath;
#property(nonatomic,retain) UIImageView *imageView;
#property(nonatomic,retain) UILabel *titleLabel1;
#property(nonatomic,retain) UILabel *titleLabel2;
#end
#IMPLEMENTATION FILE
#implementation CustomTableViewCell
#synthesize titleLabel1,titleLabel2,imageView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Your initialisation if any.
}
return self;
}
- (void)setValuesForCell:(YourModal*)modal withIndexPath:(NSIndexPath*)indexPath{
titleLabel1.text=modal.name;
titleLabel2.text=modal.description;
imageView.image=modal.image;
//Other values you want set from modal
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state.
}
- (void)dealloc {
[super dealloc];
[titleLabel1 release];
[titleLabel2 release];
//Other memory releases
}
#end
In your xib you can load the CustomTableViewCell as your class for viewing on tableview

UITableView is revealed only after it is scrolled upwards

I have a storyboard with a UIView and a UITableView in it. The UITableView has custom cells (UITableViewCell with xib).
When I run the app, only the first row of the table is shown, the rest of the table is hidden.
The rows are not seen on the screen, but they respond to user interaction as expected.
The rest of the cells are revealed only after the table is scrolled upwards.
What could be the problem?
Here is the code for UIView with the table:
#implementation EldersTableViewController
#synthesize items;
#synthesize tableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
EldersDataHendler *edh = [[EldersDataHendler alloc]init];
NSMutableArray *itemsFromPList = [edh dataForTableFrom:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"eldersData" ofType:#"plist"]]];
self.items = itemsFromPList;
[edh release];
edh=nil;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (IBAction)didPressBackButton:(UIButton *)sender {
[self.view removeFromSuperview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SEObject *cellInfo = [self.items objectAtIndex:indexPath.row];
EldersItemCell* cell = (EldersItemCell*)[tableView dequeueReusableCellWithIdentifier:#"EldersItemCell"];
if (cell == nil) {
NSArray* topObjects = [[NSBundle mainBundle] loadNibNamed:#"EldersItemCell" owner:self options:nil];
for (id obj in topObjects){
if ([obj isKindOfClass:[EldersItemCell class]]){
cell = (EldersItemCell*)obj;
break;
}
}
}
[cell setObject:cellInfo];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SEObject *cellInfo = [self.items objectAtIndex:indexPath.row];
if (!eldersDetailsViewController){
eldersDetailsViewController = [[self.storyboard instantiateViewControllerWithIdentifier:#"elderDetailsVC"] retain];
}
eldersDetailsViewController.seObject = cellInfo;
[self.view addSubview:eldersDetailsViewController.view];
}
- (void)dealloc {
[eldersDetailsViewController release];
[tableView release];
[super dealloc];
}
#end
Thanks in advance,
Luda
1st just create an object class for your cell design,then import it in your .m file.then try like this and connect the table view delegate and data source properly
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Displayfriendscell";
Displayfriendscell *cell = (Displayfriendscell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[Displayfriendscell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell...
[[cell viewWithTag:121] removeFromSuperview];
[[cell viewWithTag:151] removeFromSuperview];
friend *user = [sortedFriendsArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.nameLabel.text = user.contactNAame;
cell.nameLabel.text = user.friendName;
//cell.nameLabel.text =[[sortedFriendsArray objectAtIndex:indexPath.row] objectForKey:#"name"];
//user.friendName=[[sortedFriendsArray objectAtIndex:indexPath.row] objectForKey:#"name"];
NSLog(#"name is%#",cell.nameLabel.text);
return cell;
}
Problem solved! Thanks a lot dear arooaroo. There was something with the custom cell with the xib. So I've created a custom Table View Cell programmatically. Here is a nice tutorial

UITableViewCell image alignment to the right, possible?

when adding an image to table cell, as default it goes to left:
cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
how can I change it that every image in the UITableViewCell will go automaticlly to the right and the textLabel will be 10px to the left of the image.
Thanks alot!
Another way is to create a custom cell and override layoutSubviews method.
#interface CustomCell : UITableViewCell
#end
#implementation CustomCell
- (void)layoutSubviews
{
[super layoutSubviews];
// grab bound for contentView
CGRect contentViewBound = self.contentView.bounds;
// grab the frame for the imageView
CGRect imageViewFrame = self.imageView.frame;
// change x position
imageViewFrame.origin.x = contentViewBound.size.width - imageViewFrame.size.width;
// assign the new frame
self.imageView.frame = imageViewFrame;
}
#end
Rembember that in cellForRowAtIndexPath you need to create and reuse CustomCell and not UITableViewCell.
Hope it helps.
Edit
#import "CustomCell.h"
// other code here...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
Find the solution here code.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"foo.png"]];
cell.accessoryView = imageView;
For your reference.
UITableViewCell with image on the right?
try this:
cell.imageView.frame = CGRectMake(cell.frame.size.width - cell.imageView.frame.size.width, cell.imageView.frame.origin.y, cell.imageView.frame.size.width, cell.imageView.frame.size.height);
[cell.yourTexLabel sizeToFit];
cell.yourTexLabel.frame = CGRectMake(cell.imageView.origin.x - cell.yourTexLabel.frame.size.width - 10, cell.yourTexLabel.frame.origin.y, cell.yourTexLabel.frame.size.width, cell.yourTexLabel.frame.size.height);
Found a better answer from #TomSwift here https://stackoverflow.com/a/31616694/1884707
cell.contentView.transform = CGAffineTransformMakeScale(-1,1);
cell.imageView.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.transform = CGAffineTransformMakeScale(-1,1);
cell.textLabel.textAlignment = NSTextAlignmentRight;
By applying a transform on the contentView you can place the imageView on the right.
in swift3 and swift4, we can use this:
cell.accessoryView = UIImageView(image:UIImage(named:"imageNmae")!)
One solution is to use a custom UITableViewCell. The steps are:
Create a new objective-C class that is a subclass of UITableViewCell, for example LabeledImageTableViewCell. Declare ivars and properties for a UILabel and a UIImageView.
In Interface Builder, set the content of the UITableView to Dynamic Prototypes. Drag a UIImageView and a UILabel to a table view cell and position them. Set the cell's class to LabeledImageTableViewCell. Connect the outlets of the cell to the UILabel & UIImageView objects of LabeledImageTableViewCell.
In the delegate for UITableView (usually a UITableViewController, sometimes a UIViewController) implement the datasource methods, for example:
//#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return (NSInteger)[rowData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"tvcLabeledImage";
LabeledImageTableViewCell *cell = (LabeledImageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[LNCCorrelationInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.myImage = [UIImage imageNamed:#"imageForThisRow.png"];
cell.myLabel = "imageForThisRow";
return cell;
}
Also, check out the Apple videos from WWDC 2011, UITableView Changes, Tips & Tricks and Introducing Interface Builder Storyboarding (Login required: https://developer.apple.com/videos/wwdc/2011/.)