In my app i am having a pop over controller which shows a bunch of images when clicked from other view.The other view have some images in it.All the images have a arrow button above them clicking on which the pop over gets displayed.let me come to the issue.say e.g i clicked the arrow button above the second image and pop over gets displayed .Now when i select any image from the pop over then i want to set that image to the image view present in the main view(or the image view which consist the arrow button).But what i am getting is that when i select any image from the pop over then it always gets set to the last image view present in the main view.I want to set it on the same image view above whose arrow button is clicked to display the pop over.
my code is:-
main view:--
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
UIImageView * imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(25, 4, 80, 80)] autorelease];
UIImageView * imageView2 = [[[UIImageView alloc] initWithFrame:CGRectMake(115,4,80, 80)] autorelease];
UIImageView * imageView3 = [[[UIImageView alloc] initWithFrame:CGRectMake(205,4, 80, 80)] autorelease];
UIImageView * imageView4 = [[[UIImageView alloc] initWithFrame:CGRectMake(295,4, 80, 80)] autorelease];
imageView1.tag = j;
imageView2.tag = j+1;
imageView3.tag = j+2;
imageView4.tag = j+3;
[cell.contentView addSubview:imageView1];
[cell.contentView addSubview:imageView2];
[cell.contentView addSubview:imageView3];
[cell.contentView addSubview:imageView4];
}
for ( int i = 1; i <= j; i++ ) {
imageView = (UIImageView *)[cell.contentView viewWithTag:i];
imageView.image=nill
}
int photosInRow;
if ( (indexPath.row < [tableView numberOfRowsInSection:indexPath.section] - 1) || ([sentence count] % 4 == 0) ) {
photosInRow = 4;
} else {
photosInRow = [sentence count] % 4;
}
for ( int i = 1; i <=[sentence count]; i++ ){
imageView = (UIImageView *)[cell.contentView viewWithTag:i];
[self setImage1:imageView];
}
return cell;
}
Click event of the button:--
-(void)showPopOver:(id)sender
{
ModalView *mvc = [[ModalView alloc]init];
[mvc settingParentButton:imageView];
[mvc settingPop:detailViewPopover];
// Present the popover from the button that was tapped in the detail view.
[detailViewPopover presentPopoverFromRect:CGRectMake(0,0, 325, 650) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
// Set the last button tapped to the current button that was tapped.
[mvc release];
}
setting parent button event of modal view:--
-(void)settingParentButton:(UIImageView *)imageView {
imageView1=imageView;
}
and did select row at index path of modal view:-
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(imageView1.tag);
if (indexPath.row==0) {
[imageView1 setImage:[UIImage imageNamed:[nsmResult objectAtIndex:indexPath.row]] ];
}
if (indexPath.row==1) {
[imageView1 setImage:[UIImage imageNamed:[nsmResult objectAtIndex:indexPath.row]] ];
}
if (indexPath.row==2) {
[imageView1 setImage:[UIImage imageNamed:[nsmResult objectAtIndex:indexPath.row]] ];
}
if (indexPath.row==3) {
[imageView1 setImage:[UIImage imageNamed:[nsmResult objectAtIndex:indexPath.row]] ];
}
[pop2 dismissPopoverAnimated:YES];
}
Please help.Is it the tag issue ,please tell how can i check which tag is now in progress through which i can get the image view.Please answer.
In that imageview while creating the memory allocation,autorelease should not be given,realease your memory in the dealloc, your expected image wil be placed in your occurences.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *im = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = im;
UIImageWriteToSavedPhotosAlbum(im, nil, nil, nil);
imageView.contentMode = UIViewContentModeScaleAspectFit;
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
#interface testpViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
IBOutlet UIImageView *imageView;
}
#property (nonatomic, retain) UIImageView *imageView;
Related
I have a UICollectionView and Im trying to set a label and an image in the collectionViewCell. Unfortunately I cant seem to get any labels to display or anything else for that matter.
Here is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
}
Unfortunately no label is being displayed and neither is the text in the label.
Updated: I've added the rest of the code from this class file.
#import "ContainerListController.h"
#import "ContainerController.h"
#import "ContainerList.h"
#implementation ContainerListController
//Deallocate temp variables
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//Initiate objects
- (id)init {
if (self = [super initWithTitle:LocStr(#"CONTAINER_LIST_TITLE") navBarHidden:NO]) {
m_paths = [ContainerList shared].paths;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(onContainerListDidChange)
name:kSDKLauncherContainerListDidChange object:nil];
}
return self;
}
//Load all the views.
- (void)loadView {
//Allocate a UI view
self.view = [[UIView alloc] init];
//Create flow layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//Force Horizontal Scroll
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
layout.minimumInteritemSpacing =[[UIScreen mainScreen] bounds].size.width;
layout.minimumLineSpacing=0.0;
//Create Collection
UICollectionView *coll =[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
//Allocations
m_coll = coll;
coll.dataSource =self;
coll.delegate =self;
coll.pagingEnabled = YES;
coll.collectionViewLayout = layout;
//Customize Cells
[coll registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[coll setBackgroundColor:[UIColor orangeColor]];
[layout invalidateLayout];
//Create the subview
[self.view addSubview:coll];
//set minimum spacing
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
layout.minimumLineSpacing = 100.0f;
layout.minimumInteritemSpacing = 100.0f;
}
else{
layout.minimumLineSpacing = 40.0f;
layout.minimumInteritemSpacing = 40.0f;
}*/
//Old Layout
//UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
//m_table = table;
//table.dataSource = self;
//table.delegate = self;
//[self.view addSubview:table];
}
- (void)onContainerListDidChange {
m_paths = [ContainerList shared].paths;
[m_table reloadData];
[m_coll reloadData];
}
//Debugging components function
/*-(void)printComps:(NSArray* ) components{
for (NSInteger i =0; i<16; i++) {
NSString * item;
item=components[i];
}
}*/
//old tableview cell
- (UITableViewCell *)
tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
cell.textLabel.text = (components == nil || components.count == 0) ?
#"" : components.lastObject;
return cell;
}
//Old tableView
- (void)
tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if (c != nil) {
[self.navigationController pushViewController:c animated:YES];
}
NSLog(#"Selected an item");
}
//old TableView count for epubs
- (NSInteger)
tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section{
return m_paths.count;
}
- (void)viewDidLayoutSubviews {
//m_table.frame = self.view.bounds;
m_coll.frame = self.view.bounds;
}
//Collection View Cell Data Allocation
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *issue = [[UILabel alloc] initWithFrame:CGRectMake(0,10,cell.bounds.size.width,40)];
//UICollectionViewCell *content = [[UICollectionViewCell alloc] init];
if(indexPath.item %2 == 0){
cell.backgroundColor=[UIColor blueColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
else {
cell.backgroundColor=[UIColor redColor];
issue.text = #"Some Text";
issue.textColor = [UIColor greenColor];
issue.textAlignment = NSTextAlignmentCenter;
}
NSString *path = [m_paths objectAtIndex:indexPath.row];
NSArray *components = path.pathComponents;
NSString *Title = components.lastObject;
NSLog(#"Title: %#",Title);
NSString *Titletest = components.lastObject;
NSInteger comp1 = components.count;
NSString *comps = #"components";
NSLog(#"There are: %ld %#", (long)comp1,comps);
NSLog(#"Title: %#",Titletest);
for (NSInteger i =0; i<15; i++) {
NSString * item;
item=components[i];
NSLog(#"Component:%ld %#",(long)i,components[i]);
}
return cell;
}
//Collection View Cell Data De-Allocation
- (void)
collectionView:(UICollectionView *)collectionView
numberofItemsInSection:(NSIndexPath *)indexPath{
[collectionView deselectItemAtIndexPath:indexPath animated:YES];
NSString *path = [m_paths objectAtIndex:indexPath.row];
ContainerController *c = [[ContainerController alloc] initWithPath:path];
if(c !=nil){
[self.navigationController pushViewController:c animated:YES];
}
}
//Collection
-(NSInteger)
collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
return m_paths.count;
}
//Set Collection View Cell Size
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set Landscape size of cells
/*if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60;
NSLog(#"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
}
//Set Potrait size of cells
else{
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160;
NSLog(#"Is Portrait");
return CGSizeMake(cellWidth, cellHeigt);
}*/
return CGSizeMake(collectionView.bounds.size.width, collectionView.bounds.size.height);
}
//Collection View Cell Position
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(150.0,0.0,150.0,0.0); // top, left, bottom, right
}
else{
return UIEdgeInsetsMake(20.0,0.0,0.0,0.0); // top, left, bottom, right
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
[m_coll performBatchUpdates:nil completion:nil];
}
-(void)viewWillTransitionToSize:withTransitionCoordinator{
[m_coll performBatchUpdates:nil completion:nil];
}
/*-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(#"Changed to landscape Spacing");
return inset;
}
else{
return inset;
}
}*/
#end
Clear example to use custom collectionViewCell.
Create a separate class subclass ofUICollectionViewCell see below code:
.h file:
#import <UIKit/UIKit.h>
#interface CollectionViewCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UILabel *customLabel;
#end
.m file:
#import "CollectionViewCell.h"
#implementation CollectionViewCell
#end
Now drag and drop the collectionView inside viewController using storyboard then by selecting cell set custom class for it and connect its IBOutlet of label see below image.
Setting up custom class:
Connecting label's outlet: if adding label and other ui component from storyboard
Note: Drag uilabel inside cell before you connect its IBOutlet.
Now configure cell inside your viewController class. And configure collectionView correctly by connecting its delegate, dataSuorce and IBOutlet.
#import "ViewController.h"
#import "CollectionViewCell.h"
#interface ViewController (){
// instance variable deceleration part
NSMutableArray *yourArray;
}
#end
#implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
_yourCollView.delegate = self;
_yourCollView.dataSource = self;
yourArray = [[NSMutableArray alloc] initWithObjects:#"1st cell",#"2nd cell",#"3rd cell",#"4th cell", nil];
// Do any additional setup after loading the view, typically from a nib.
}
// collection view delegate methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [yourArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"MyCustomCell" forIndexPath:indexPath];
// configuring cell
// cell.customLabel.text = [yourArray objectAtIndex:indexPath.row]; // comment this line if you do not want add label from storyboard
// if you need to add label and other ui component programmatically
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)];
label.tag = 200;
label.text = [yourArray objectAtIndex:indexPath.row];
// this adds the label inside cell
[cell.contentView addSubview:label];
return cell;
}
//Note: Above two "numberOfItemsInSection" & "cellForItemAtIndexPath" methods are required.
// this method overrides the changes you have made to inc or dec the size of cell using storyboard.
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100, 100);
}
} // class ends
Setup the cell identifier (by selecting a cell) MyCustomCell you have given inside cellForItemAtIndexPath method before use see below image:
Note: Change the text color of uilabel to white before because by default collectionView appears black.
Hope here you understand.
Create subclass of UICollectionViewCell. For instance TestCollectionViewCell.
In Storyboard drag label in cell and set "Custom class" for this UICollectionViewCell with your created class. Set Reusable identifier, if your collection view in UIViewController don't forget to set DataSource and Delegate for that collectionView.
Connect IBOutlet in your Cell subclass.
Set at least 1 value inside numberOfItemsInSection method.
Then use your subclass of cell in cellForItemAt and try set text for a label.
You are missing the:
[cell.contentView addSubview:issue];
The program has a tableview. Each TableViewCell has a UICollectionView. When user drag and drop the one of the categories label, the program will add a UICollectionViewCell which has a UIView. It works well. However, when user scroll the tableview then the UICollectionView won't render properly. The display is as below.
This is the pic before user scroll the view.
http://cl.ly/image/1P0s3Z0m443t
After user scroll the view, there is a promise overlap the sin. The promise cell shouldn't be there.
http://cl.ly/image/3L2M1s3s3F0X
Here is my code of cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
// Configure the cell..
/*
There is no UITableViewCell in the storyboard
*/
ContentViewCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel * cellLabel = nil; //The cellLabel is for rendering the bible verses
if (cell==nil) {
cell = [[ContentViewCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
/*
To Make Dynamic Cell Height
*/
cellLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[cellLabel setNumberOfLines:0];
[cellLabel sizeToFit];
[cellLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[cellLabel setTag:1];
[[cell contentView] addSubview:cellLabel];
}
NSString * text = [verseArray objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGRect rectangular = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName: [UIFont systemFontOfSize:FONT_SIZE]} context:nil];
CGSize size = rectangular.size;
/*
When There Are Rows More Than One Screen
*/
if (!cellLabel) {
cellLabel = (UILabel *)[cell viewWithTag:1];
}
cell.CellContent = text;
[cellLabel setText:text];
[cellLabel setFrame:CGRectMake((self.view.frame.size.width*0.39), 0, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))]; //To Locate The Position Of The Label In The Cell
cell.userInteractionEnabled = TRUE;
return cell;
}
And this is ContentViewCustomTableViewCell
#import "ContentViewCustomTableViewCell.h"
#import "AnswerCollectionViewCell.h"
#implementation ContentViewCustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(3, 3, 2, 2);
layout.itemSize = CGSizeMake(30, 10);
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
self.collectionView = [[AFIndexedCollectionView alloc] initWithFrame:CGRectZero
collectionViewLayout:layout];
[self.collectionView registerClass:[AnswerCollectionViewCell class]forCellWithReuseIdentifier:CollectionViewCellIdentifier];
self.collectionView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1];
self.collectionView.showsVerticalScrollIndicator = NO;
[self.contentView addSubview:self.collectionView];
}
return self;
}
- (void)awakeFromNib
{
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)layoutSubviews
{
[super layoutSubviews];
self.collectionView.frame = CGRectMake(10, 10, 110, 50);
}
-(void)setCollectionViewDataSourceDelegate:(id<UICollectionViewDataSource, UICollectionViewDelegate>)dataSourceDelegate index:(NSInteger)index
{
self.collectionView.dataSource = dataSourceDelegate;
self.collectionView.delegate = dataSourceDelegate;
self.collectionView.index = index;
[self.collectionView reloadData];
}
#end
In my tableView, in some cells i have added an imageView as subview of cell contentView. On scrolling tableView up and down these images duplicating on other cells also. But this problem doesn't occur always. Please suggest a solution.. I am using the following code.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (friendsArray.count != 0)
{
NSString *str = [friendsIdArray objectAtIndex:indexPath.row];
if ([pendingRequests containsObject:str])
{
// Add image for pending item
UIImageView *pendImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pendng.png"]];
pendImage.frame = CGRectMake(220.0, 2.5, 70, 40);
pendImage.tag = indexPath.row;
[cell.contentView addSubview:pendImage];
}
}
}
NSString *object;
if (friendsArray.count == 0)
{
if ([cell.contentView viewWithTag:indexPath.row])
{
for (UIView *subview in [cell.contentView subviews])
{
[subview removeFromSuperview];
}
}
object = #"No friends added to the list";
cell.textLabel.textAlignment = UITextAlignmentCenter;
}
else
{
object = [friendsArray objectAtIndex:indexPath.row];
cell.textLabel.textAlignment = UITextAlignmentLeft;
if (![cell.contentView viewWithTag:indexPath.row])
{
NSString *str = [friendsIdArray objectAtIndex:indexPath.row];
if ([pendingRequests containsObject:str])
{
// Add image for pending item
UIImageView *pendImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pendng.png"]];
pendImage.frame = CGRectMake(220.0, 2.5, 70, 40);
pendImage.tag = indexPath.row;
[cell.contentView addSubview:pendImage];
}
}
}
The problem is solved now. I have used the following line inside the else case of creating new tableViewCell.
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
I have edited my code as shown below :
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
else
{
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
}
As Romit Mewada suggested you can use that but each time you have alloc & add new UIImageView.
Instead of that you can send nil to the image of that UIImageView.
Implement in this way.
if (cell == nil)
{
//get your cell or alloc & initialize
// create and add imageView
}
UIImageView* imageView = [cell.contentView viewWithTag:indexPath.row];
imageView.image = nil;
//do your other task, you can use the same imageView to add other image for other row.
Try this below code..
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (friendsArray.count != 0)
{
NSString *str = [friendsIdArray objectAtIndex:indexPath.row];
if ([pendingRequests containsObject:str])
{
// Add image for pending item
UIImageView *pendImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pendng.png"]];
pendImage.frame = CGRectMake(220.0, 2.5, 70, 40);
pendImage.tag = indexPath.row;
[cell.contentView addSubview:pendImage];
}
}
NSString *object;
if (friendsArray.count == 0)
{
if ([cell.contentView viewWithTag:indexPath.row])
{
for (UIView *subview in [cell.contentView subviews])
{
[subview removeFromSuperview];
}
}
object = #"No friends added to the list";
cell.textLabel.textAlignment = UITextAlignmentCenter;
}
else
{
object = [friendsArray objectAtIndex:indexPath.row];
cell.textLabel.textAlignment = UITextAlignmentLeft;
if (![cell.contentView viewWithTag:indexPath.row])
{
NSString *str = [friendsIdArray objectAtIndex:indexPath.row];
if ([pendingRequests containsObject:str])
{
// Add image for pending item
UIImageView *pendImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pendng.png"]];
pendImage.frame = CGRectMake(220.0, 2.5, 70, 40);
pendImage.tag = indexPath.row;
[cell.contentView addSubview:pendImage];
}
}
}
}
I have a table view, and I am adding four UIImageViews to a row, so in total I have five rows and twenty image views. I am inserting images one by one into the cell. The second row will only start to fill once all four image views are filled.
I need some logic for this. I mean, how can I check which place is next to be filled in the table view and at which event? How can I add images one by one to the UIImageViews? Also, initially only two rows will be shown. After filling these two rows, when images begin to enter into the third row, I need to show an icon adjacent to the last row that is on the screen, to tell the user that there is more data below. Also, is there any event to detect which row is currently the last row on screen?
Also is there any way to individually select the images from a row?
Run this code:-
.h file code
#import <UIKit/UIKit.h>
#interface helpTableViewController : UIViewController {
IBOutlet UITableView *gridTableView;
NSMutableArray *imagesArray;
int widthview,widthview1;
}
#property(nonatomic,retain)NSMutableArray *imagesArray;
#property(nonatomic,retain)UITableView *gridTableView;
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath;
-(void)crossViewButtonClicked:(UIButton *)sender;
#end
.m file code:-
#synthesize gridTableView;
#synthesize imagesArray;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *tempArray=[[NSMutableArray alloc]init];
self.imagesArray=tempArray;
[tempArray release];
[self.imagesArray addObject:[UIImage imageNamed:#"pic1.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic2.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic3.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic4.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic5.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic6.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic1.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic2.png"]];
[self.imagesArray addObject:[UIImage imageNamed:#"pic3.png"]];
widthview=0;
widthview1=0;
}
- (void)viewDidUnload {
self.gridTableView=nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[imagesArray release];
[gridTableView release];
[super dealloc];
}
#pragma mark -
#pragma mark TableView Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=nil;
if (cell == nil) {
cell =[self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
}
return cell;
}
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
if (indexPath.row==0) {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
scrollView.contentSize = CGSizeMake(320, 180);
scrollView.backgroundColor=[UIColor clearColor];
scrollView.showsHorizontalScrollIndicator = NO;
[cell.contentView addSubview:scrollView];
for (int i=0; i<4;i++) {
UIView *profileView=[[UIView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
profileView.backgroundColor=[UIColor whiteColor];
UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 8, 83, 106)];
[profileimageView setImage:[self.imagesArray objectAtIndex:i]];
profileimageView.tag=i+90;
[profileView addSubview:profileimageView];
[profileimageView release];
[scrollView addSubview:profileView];
widthview=widthview+105;
NSLog(#"%d",widthview);
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(widthview1+10, 12, 95, 155)];
//button.contentMode = UIViewContentModeScaleAspectFill;
button.tag=999999;
[button setBackgroundColor:[UIColor greenColor]];
[button addTarget:self action:#selector(imageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
widthview=widthview+105;
scrollView.contentSize = CGSizeMake(widthview, 180);
}
if (indexPath.row==1) {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
scrollView.contentSize = CGSizeMake(320, 180);
scrollView.backgroundColor=[UIColor clearColor];
scrollView.showsHorizontalScrollIndicator = NO;
[cell.contentView addSubview:scrollView];
for (int i=0; i<4;i++) {
UIView *profileView=[[UIView alloc]initWithFrame:CGRectMake(widthview1+10, 12, 95, 155)];
profileView.backgroundColor=[UIColor whiteColor];
UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 8, 83, 106)];
// [profileimageView setImage:[UIImage imageNamed:#"gridimage1.png"]];
profileimageView.tag=4+i;
[profileimageView setImage:[self.imagesArray objectAtIndex:3+i]];
[profileView addSubview:profileimageView];
[scrollView addSubview:profileView];
[profileimageView release];
widthview1=widthview1+105;
NSLog(#"%d",widthview1);
}
scrollView.contentSize = CGSizeMake(widthview1, 180);
}return cell;
}
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#pragma mark -
#pragma mark button methods
-(void)imageButtonClicked:(UIButton *)sender
{
[self.imagesArray replaceObjectAtIndex:0 withObject:[UIImage imageNamed:#"abdulprofilepic.png"]];
[self.gridTableView reloadData];
}
You should keep all of the logic (and data) in your table view controller (UITableViewController subclass). I suggest you have a custom UITableViewCell subclass that can hold 4 images (the cell itself should be responsible for the layout), and the table view controller is responsible for setting it up. In -tableView:cellForRowAtIndexPath: you can look at your collection of images, then just use modular arithmetic to figure out which images should be in the cell for that particular index path.
As for individually selecting images, perhaps you could have your cells know their index path (set as a custom property in -tableView:cellForRowAtIndexPath:), then each have a delegate method telling your controller that a certain image was pressed (for example, -cellAtIndexPath:didSelectImageAtIndex:).
try this,
As there are fix number of images that you want to show in your row i. e. 4
So what you have to do is:-
in .h file
int widthview,widthview1;
in .m file in viewdidload
widthview=0;
widthview1=0;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;//to remove blu selection color
return cell;
}
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
if (indexPath.row==0) {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
scrollView.contentSize = CGSizeMake(320, 180);
scrollView.backgroundColor=[UIColor clearColor];
scrollView.showsHorizontalScrollIndicator = NO;
[cell.contentView addSubview:scrollView];
for (int i=0; i<4;i++) {
UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
[profileimageView setImage:[self.imagesArray objectAtIndex:i]];
[profileimageView release];
[scrollView addSubview:profileimageView];
widthview=widthview+105;
NSLog(#"%d",widthview);
}
scrollView.contentSize = CGSizeMake(widthview, 180);
}
if (indexPath.row==1) {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
scrollView.contentSize = CGSizeMake(320, 180);
scrollView.backgroundColor=[UIColor clearColor];
scrollView.showsHorizontalScrollIndicator = NO;
[cell.contentView addSubview:scrollView];
for (int i=0; i<4;i++) {
UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
[profileimageView setImage:[self.imagesArray objectAtIndex:4+i]];
[profileimageView release];
[scrollView addSubview:profileimageView];
widthview1=widthview1+105;
NSLog(#"%d",widthview1);
}
scrollView.contentSize = CGSizeMake(widthview1, 180);
}
return cell;
}
This code is for 2 rows do the same thing for next three rows.
Adjust the coordinates according to your requirement.
hope this will save your time.
answer for Also is there any way to individually select the images from a row? :
Give image to button and add that button inside row!!
I am creating an application and I have a customized header of tableview. But sometimes the header gets duplicated. It takes the place of a row in tableview. How do I solve this strange problem? BTW, my tableviewstyle is plain, Header height is 44.0 and the footer height is 0.0. Here is an image how it displays. The header "comments" is duplicated just below the header "Messages" while it should be the row.
Here is the complete implementation of this view
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
TitleForSectionView=[[NSArray arrayWithObjects:#"Dates To Remember",#"Messages",#"Comments",#"Wishlist",#"Reminders",#"Bookmarks",nil] retain];
self.MySectionIndexArray=[[NSMutableArray alloc] init];
[self.MySectionIndexArray addObject:#"UP"];
[self.MySectionIndexArray addObject:#"DOWN"];
[self.MySectionIndexArray addObject:#"DOWN"];
[self.MySectionIndexArray addObject:#"DOWN"];
[self.MySectionIndexArray addObject:#"DOWN"];
[self.MySectionIndexArray addObject:#"DOWN"];
self.IconsForSectionsView=[[NSMutableArray alloc] init];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconCalender.png"]];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconMessage.png"]];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconComments.png"]];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconWishList.png"]];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconReminder.png"]];
[self.IconsForSectionsView addObject:[UIImage imageNamed:#"IconBookMark.png"]];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([[self.MySectionIndexArray objectAtIndex:section] isEqualToString:#"UP"]) {
return 4;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *MyDashBoardCell=nil;
static NSString *AddNewDateCellIdentifier=#"AddNewDateCell";
static NSString *CellIdentifier = #"DashBoardCell";
DashBoardCustomCellObject = (DashBoardCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (DashBoardCustomCellObject == nil) {
[[[[NSBundle mainBundle] loadNibNamed:#"DashBoardCustomCell" owner:self options:nil] retain]autorelease];
}
[DashBoardCustomCellObject SetDashBoardCellData:#"Mar 9" EventText:#"My Birthday"];
AddNewDateCellObject = (AddNewDateCell *)[tableView dequeueReusableCellWithIdentifier:AddNewDateCellIdentifier];
if (AddNewDateCellObject == nil) {
[[[[NSBundle mainBundle] loadNibNamed:#"AddNewDateCell" owner:self options:nil] retain]autorelease];
}
if(indexPath.section==0 && indexPath.row==0)
{
MyDashBoardCell=AddNewDateCellObject;
}
else
{
MyDashBoardCell=DashBoardCustomCellObject;
}
return MyDashBoardCell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label and button and icon image
self.customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.bounds.size.width,44)] autorelease];
self.customView.backgroundColor=[UIColor whiteColor];
// create image object
UIImageView *icon= [[[UIImageView alloc] initWithImage:[self.IconsForSectionsView objectAtIndex:section]] autorelease];
icon.contentMode=UIViewContentModeCenter;
icon.frame = CGRectMake(0,0,40,40);
// create the label objects
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.font = [UIFont boldSystemFontOfSize:13];
headerLabel.frame = CGRectMake(53,11,172,21);
headerLabel.text = [TitleForSectionView objectAtIndex:section];
headerLabel.textColor = [UIColor blackColor];
headerLabel.highlightedTextColor=[UIColor whiteColor];
// create the button objects
ButtonDrop = [[[UIButton alloc] initWithFrame:CGRectMake(278, 9, 25, 25)] autorelease];
ButtonDrop.tag=section;
if ([[self.MySectionIndexArray objectAtIndex:section] isEqualToString:#"UP"])
{
[ButtonDrop setBackgroundImage:[UIImage imageNamed:#"Up.png"] forState:UIControlStateNormal];
self.customView.backgroundColor=[UIColor blueColor];
headerLabel.highlighted=YES;
}
else
{
[ButtonDrop setBackgroundImage:[UIImage imageNamed:#"Down.png"] forState:UIControlStateNormal];
}
[ButtonDrop addTarget:self action:#selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
[self.customView addSubview:icon];
[self.customView addSubview:headerLabel];
[self.customView addSubview:ButtonDrop];
return self.customView;
}
- (void)checkAction:(id)sender
{
UIButton *Button = (UIButton*)sender;
NSLog(#"Button Tag=%d",Button.tag);
if([[self.MySectionIndexArray objectAtIndex:Button.tag] isEqualToString:#"UP"])
{
[self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:#"DOWN"];
[ButtonDrop setBackgroundImage:[UIImage imageNamed:#"Up.png"] forState:UIControlStateNormal];
}
else
{
[self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:#"UP"];
[ButtonDrop setBackgroundImage:[UIImage imageNamed:#"Down.png"] forState:UIControlStateNormal];
}
[TableDashBoard reloadSections:[NSIndexSet indexSetWithIndex:Button.tag] withRowAnimation:UITableViewRowAnimationFade];
}
Try having a zero-height row for your empty sections. That seems to make them draw correctly for me.
I think there are a couple of explainations:
(1) You're displaying the section header of an empty section which would cause two headers to appear one on top of the other with no rows in between.
(2) You are returning a header view as a row cell in – tableView:cellForRowAtIndexPath: Since the header "it takes place of a row in tableview" I think this the most likely explanation. Check – tableView:viewForHeaderInSection: as well.