Adjusting code to include Lazy loading - scrollview and images - ios

Im trying to refactor my code for better memory management and performance. I have an array of 12 images, but I want to load them as needed, not all at the same time. So maybe the current image -1, the current image and the current image +1. I viewed some of the answers on SO but found them unclear. I felt it would be clearer if I posted my code for reference.
//scroll view set up
- (void)scrollViewSetUp
{
self.scrollview.delegate = self;
for (int i = 0; i < _images.count; i++)
{
CGRect frame;
frame.origin.x = self.scrollview.frame.size.width * i;
frame.size = self.scrollview.frame.size;
self.scrollview.pagingEnabled = YES;
UIImageView *subview = [[UIImageView alloc] initWithFrame:frame];
subview.image = [UIImage imageNamed:[_images objectAtIndex:i]];
[self.scrollview addSubview:subview];
}
self.scrollview.contentSize = CGSizeMake(self.scrollview.frame.size.width * _images.count, self.scrollview.frame.size.height);
self.automaticallyAdjustsScrollViewInsets = NO;
//page control ie .... at bottom of
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(100.0,0.0,100.0,40.0)];
[self.pageControl setNumberOfPages:_images.count];
[self.pageControl setCurrentPage:0];
self.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
[self.pageControl setBackgroundColor:[UIColor clearColor]];
[self.viewForPageControl addSubview:self.pageControl];
[self.viewForPageControl setBackgroundColor:[UIColor clearColor]];
}
#pragma mark - UIScrollView Delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
int newOffset = scrollView.contentOffset.x;
int newPage = (int)(newOffset/(scrollView.frame.size.width));
[_pageControl setCurrentPage:newPage];
}
Any advice or direction is greatly appreciated.

As per Gman's request I reposted my comment.
This tutorial will help you:
http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content

You could try to reuse your UIImageView as they go offscreen... but you'll be just trying to redo what UITableview already does. UITableView with a custom UITableViewCell would take care of notifying you when new cells comes visible and dequeuing the ones that are offscreen.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"yourCustomImageCell";
//look if there are cells that could be reused
CustomImageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) { //if not, create a new one
cell = [[CustomImageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
//Set your image here
return cell;
}

Not sure if this is the best way of doing it, but it's an option.
You can set the tag property on your UIImageView to correspond to your index in your loop when setting the scrollView.
Then in your scrollViewDidEndDecelerating method:
for (int i = 0; i < _salonImages.count; i++)
{
if(i == (newPage-1))
{
UIImageView *imgView = (UIImageView*)[self.scrollView viewWithTag:newPage-1];
imgView.image = [_images objectAtIndex:newPage-1];
}
else if(i == newPage)
{
UIImageView *imgView = (UIImageView*)[self.scrollView viewWithTag:newPage];
imgView.image = [_images objectAtIndex:newPage];
}
else if(i == (newPage + 1 ))
{
UIImageView *imgView = (UIImageView*)[self.scrollView viewWithTag:newPage+1];
imgView.image = [_images objectAtIndex:newPage+1];
}
else
{
UIImageView *imgView = (UIImageView*)[self.scrollView viewWithTag:i];
imgView.image = nil;
}
}

Related

Nested UIScrollView not paging for Internal UIScrollView

I am trying to build a screen which has 2 UIScrollViews, 1 Main Scroll View which is used as a container and to scroll vertically (this is working fine).
Inside the Main Scroll View, is a second scroll view, which is used for display different images. This needs to be scrolled horizontally so it will page to other images which will also update content details displayed in the Main Scroll View.
When attempting to get these two features to work together, the paging functionality does not work, however if it is outside the main scroll view it will work but will not scroll with the rest of the content.
The Image Scroll View is being detected in the events as well, but doesn't show any ability to scroll.
Below are my 3 functions which are performing the work.
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up the Image Scroll View
ImageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, screenWidth, homeImage)];
ImageScrollView.scrollEnabled = YES;
ImageScrollView.userInteractionEnabled=YES;
[ImageScrollView setPagingEnabled:YES];
[ImageScrollView setAlwaysBounceVertical:NO];
ImageScrollView.delegate = self;
// Set up the image array
NSArray *imagesArray = [NSArray arrayWithObjects:#"staff1big.png", #"staff2big.png", #"staff3big.png", nil];
// Create each image subview
for (int i = 0; i < [imagesArray count]; i++)
{
CGFloat xOrigin = i * ImageScrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, ImageScrollView.frame.size.width, ImageScrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[imagesArray objectAtIndex:i]]];
[ImageScrollView addSubview:imageView];
}
// Set the Content Size and Offset
[ImageScrollView setContentSize:CGSizeMake(ImageScrollView.frame.size.width * [imagesArray count], ImageScrollView.frame.size.height)];
[ImageScrollView setContentOffset:CGPointMake(screenWidth*currentIndex, 0)];
// Get the staff object
dataSource = [DataSource dataSource];
NSArray *staffArray = [dataSource getStaff];
// Setup the Pager Control
self.pageControl = [[UIPageControl alloc] init];
NSInteger placement = (screenWidth/2)-50;
self.pageControl.frame = CGRectMake(placement, homeImage-30, 100, 20);
self.pageControl.numberOfPages = [staffArray count];
self.pageControl.currentPage = currentIndex;
[self setStaff:staffArray[currentIndex]];
// Add the Main Scroll View
MainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
MainScrollView.delegate = self;
MainScrollView.scrollEnabled = YES;
MainScrollView.userInteractionEnabled=YES;
// Add each object to the correct scroll view
[ImageScrollView addSubview:self.pageControl];
[MainScrollView addSubview:ImageScrollView];
[MainScrollView addSubview:lineView];
[self setDisplayContent]; // note the MainScrollView is added to the self.view in this method along with setting the content size to screenWidth and height is determine by the generated content.
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = ImageScrollView.frame.size.width;
float fractionalPage = ImageScrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
currentIndex = page;
self.pageControl.currentPage = page;
[self displayContent];
}
- (void)displayContent
{
int i = currentIndex;
if (i < 0)
{
i = 0;
} else if (i > 2) {
i = 2;
}
[self setStaff:allStaff[i]];
// remove all from view
for(UIView *subview in [MainScrollView subviews]) {
[subview removeFromSuperview];
}
NSArray *imagesArray = [NSArray arrayWithObjects:#"staff1big.png", #"staff2big.png", #"staff3big.png", nil];
for (int i = 0; i < [imagesArray count]; i++)
{
CGFloat xOrigin = i * ImageScrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, ImageScrollView.frame.size.width, ImageScrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[imagesArray objectAtIndex:i]]];
[ImageScrollView addSubview:imageView];
}
[ImageScrollView setContentSize:CGSizeMake(ImageScrollView.frame.size.width * [imagesArray count], ImageScrollView.frame.size.height)];
[ImageScrollView setContentOffset:CGPointMake(screenWidth*currentIndex, 0)];
// Get the staff
dataSource = [DataSource dataSource];
NSArray *staffArray = [dataSource getStaff];
self.pageControl = [[UIPageControl alloc] init];
NSInteger placement = (screenWidth/2) - 50;
self.pageControl.frame = CGRectMake(placement, homeImage-30, 100, 20);
self.pageControl.numberOfPages = [staffArray count];
self.pageControl.currentPage = currentIndex;
[self setStaff:staffArray[currentIndex]];
[ImageScrollView addSubview:self.pageControl];
[MainScrollView addSubview:ImageScrollView];
[MainScrollView addSubview:lineView];
[self setDisplayContent];
}
I do need to refactor some of the code to make more efficient, but at this stage I am just trying to get the horizontal paging to scroll horizontally.
If anyone would possibly be able to help point me in the right direction as to how to fix this issue, it would be greatly appreciated.
Here is a visual of the UI that I am trying to keep but have the image scroll horizontal.
Staff Display

How to make smooth UITableView in objective-C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working with an IOS application. In my project have several UITableView with many rows, and each row has two images. When I scroll fast then It can't load cells smoothly. How can I scroll smoothly ???
N.B: I don't want to load all rows at a time.
Please Help
Edited:
Here is my code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
float sca=appDelegate.deviceScaleFloat;
float XOffset=0*sca;
cell = [[UITableViewCell alloc] init];
cell.opaque = YES;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImage *backImg;
backImg= [UIImage imageNamed:[NSString stringWithFormat:#"background-goal-collect%#.png",ipadExtention]];
backImg=[self scaleWithScaleFactor:backImg];
UIImageView *btnBuyImageView=[[UIImageView alloc]initWithImage:backImg];
btnBuyImageView.frame=CGRectMake(XOffset, 0, backImg.size.width, backImg.size.height);
[cell.contentView addSubview: btnBuyImageView];
for (int i=0; i<5 && indexPath.row*5+i<[catFishes count]; i++) {
int productIndex = (int)indexPath.row*5 + i;
DBProductAttributes *productAttributes = [allProductAttributes objectAtIndex:productIndex];
DBProductInfo *productInfo = [catFishes objectAtIndex:productIndex];
UIImage *frameImage = [UIImage imageNamed:[NSString stringWithFormat:#"background-element-%d%#.png",productAttributes.elementid,ipadExtention]];
frameImage=[self scaleWithScaleFactor:frameImage];UIImageView *frameView = [[UIImageView alloc] initWithImage:frameImage];
frameView.frame = CGRectMake((frameImage.size.width*i)+10*sca+5*i*sca, 5*sca , frameImage.size.width, frameImage.size.height);
frameView.userInteractionEnabled=YES;
[cell.contentView addSubview:frameView];
MyTapGestureRecognizer *tapGesture=[[MyTapGestureRecognizer alloc] init];
tapGesture.tag=productIndex;
[tapGesture addTarget:self action:#selector(buttonClicked:)];
[frameView addGestureRecognizer:tapGesture];
NSString *IconStr = [NSString stringWithFormat:#"i%db.png", productInfo.productid];
UIImage *btnImg = [UIImage imageNamed:IconStr];
if(![self isProductPurchesed:productInfo.productid])
{
if([ITIWAppDelegate blackimageforstore]>0)
{
btnImg = [self getBlackAndWhiteVersionOfImage:btnImg];
}
}
UIImageView *imageIconView;
imageIconView = [[UIImageView alloc] initWithImage:btnImg];
imageIconView.frame = CGRectMake(frameView.frame.origin.x+frameImage.size.width-64*sca, frameView.frame.origin.y/*+frameImage.size.height-64*sca*/ , 64*sca, 64*sca);
imageIconView.opaque = YES;
[cell.contentView addSubview:imageIconView];
UILabel *name;
name = [[UILabel alloc] initWithFrame:CGRectMake(frameView.frame.origin.x, frameView.frame.origin.y+62*sca, frameImage.size.width-0*sca, 18.0f*sca)];
name.text = productInfo.product_name;
name.font = [UIFont fontWithName:#"Georgia" size:12.0f*sca];
name.adjustsFontSizeToFitWidth = YES;
name.textAlignment = NSTextAlignmentCenter;
if(![self isProductPurchesed:productInfo.productid])
name.backgroundColor=[UIColor grayColor];
else
name.backgroundColor = [UIColor colorWithRed:colorCodeDragonBook[productAttributes.elementid-1][0]/255.0f green:colorCodeDragonBook[productAttributes.elementid-1][1]/255.0f blue:colorCodeDragonBook[productAttributes.elementid-1][2]/255.0f alpha:1.0f];
name.textColor = [UIColor colorWithWhite:1.0 alpha:1.0];
//name.shadowColor = [UIColor blackColor];
name.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
[cell.contentView addSubview:name];
NSArray *otherElements = [productAttributes.otherElementid componentsSeparatedByString:#","];
int k=0;
UIImage *habitatFlag = [UIImage imageNamed:[NSString stringWithFormat:#"flag-%d.png",productAttributes.elementid]]; UIImageView *habitatFlagView = [[UIImageView alloc] initWithImage:habitatFlag];
habitatFlagView.frame = CGRectMake(frameView.frame.origin.x-1*sca, frameView.frame.origin.y-1*sca , 15*sca, 22*sca);
[cell.contentView addSubview:habitatFlagView];
k+=15;
for (int i=0; i<[otherElements count]; i++) {
int otherElementid = [[otherElements objectAtIndex:i] intValue];
if(otherElementid==productAttributes.elementid) continue;
UIImage *habitatFlag = [UIImage imageNamed:[NSString stringWithFormat:#"flag-%d.png",otherElementid]]; UIImageView *habitatFlagView = [[UIImageView alloc] initWithImage:habitatFlag];
habitatFlagView.frame = CGRectMake(frameView.frame.origin.x+k*sca-1*sca, frameView.frame.origin.y-1*sca , 15*sca, 22*sca);
[cell.contentView addSubview:habitatFlagView];
k+=15;
}
}
return cell;
}
Problem is occurring when the cells are going to off screen, the tableview release all cells of off screen. And when after that I want to scroll the cells are reloading. I think it is not optimal to load cells. But I don't know how to optimize this.
the best you have to do is load the images asynchronously, and not in the main thread.
If you want, you can use my ImageLoader project : https://github.com/celian-m/ImageLoader/blob/master/ImageLoader.swift
All you have to do is using CMImageView instead of UIImageView.
Then you can do [myImageView assignImageFromUrl:YOUR_URL]
This will load your images in the background thread, in FIFO mode, and save it in memory and disk cache ( i.e. : you need to load each image only 1 time ).
You can make use of SDWebImageCache so that it'll cache the images in disk and the loading of images becomes much faster.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
//set image here
});
What about setting the image async in the tableview callback:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
May I ask whether the images are web images or local images?

strage uitableview cell behavior: view moves inside cell

I am having some strange uitableview behavior- my customs cells have a little extra space around them that I cannot fix. I can also move the cells in that space. I have attached a couple of pictures as my English is not letting me to explain better. Any ideas on what might the issue be? I can post my code for my custom cell but it even happens with admob add cell, so I am not sure it is related to the custom cell.
EDIT: Added code for heights
EDIT2: I changed the scroll view alloc to
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width,self.bounds.size.height)];
And it fixed the moving of the cell. But that white line is still there.
Table View
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// return (self.tableViewHome.bounds.size.height-49-6-self.tableViewHome.tableHeaderView.bounds.size.height-self.tableViewHome.tableFooterView.bounds.size.height-GAD_SIZE_320x50.height)/3;
float height = self.tableViewHome.frame.size.height-self.tableViewHome.tableHeaderView.bounds.size.height-30.0;
if (indexPath.item==5)
{
height=kGADAdSizeBanner.size.height;
}
else
{
if (indexPath.item==1 || indexPath.item==3)
{
height=15.0;
}
else
{
if (indexPath.item==0 || indexPath.item==2 || indexPath.item==4)
{
height=(height-kGADAdSizeBanner.size.height)/3;
}
}
}
NSLog(#"Height:%f",height);
return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.1;
}
Custom Cell
-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[scrollView setShowsHorizontalScrollIndicator:NO];
[scrollView setShowsVerticalScrollIndicator:NO];
// NSInteger viewcount= 3;
// for(int i = 0; i< viewcount; i++) {
// CGFloat x = 2 * self.bounds.size.width;
todayView = [HomeTodayView homeTodayView];
todayView.frame = CGRectMake(0, 0,self.bounds.size.width, self.bounds.size.height);
todayView.backgroundColor = [UIColor redColor];
avgView = [HomeAvgView homeAvgView];
avgView.frame = CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
// [[HomeTodayView alloc] initWithFrame:
todayView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
avgView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[scrollView addSubview:todayView];
[scrollView addSubview:avgView];
scrollView.contentSize = CGSizeMake(self.bounds.size.width *2, self.bounds.size.height+100);
scrollView.pagingEnabled = YES;
scrollView.bounces = NO;
[self addSubview:scrollView];
}
return self;
}
Try This:
[table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
NOTE:- table = your tableview name.
If this does not work then please check that your custom cell height and the row height of tableView are same?

How to fix a Table view cell title text overlap each when it is scrolled

I have a table view and when it scrolls the cell title text overlap each other.
I'm I setting up the cellForIndexPath: incorrectly?
here's my cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath{
BOOL isLandscape = YES;
if (nextOrientation == UIInterfaceOrientationPortrait || nextOrientation == UIInterfaceOrientationPortraitUpsideDown) {
isLandscape = NO;
}
UIImageView* bgImage;
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:(isLandscape) ? #"landscape-cell":#"portrait-cell"];
if (cell == nil){
// cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:(isLandscape) ? #"landscape-cell":#"portrait-cell"] autorelease];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:(isLandscape) ? #"landscape-cell":#"portrait-cell"] autorelease];
if (isLandscape) {
bgImage = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, 125)] autorelease];
[bgImage setTag:BACK_IMAGE];
//
[cell addSubview:bgImage];
}else {
bgImage = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 125)] autorelease];
[bgImage setTag:BACK_IMAGE];
[cell addSubview:bgImage];
}
}else {
bgImage = (UIImageView*)[cell viewWithTag:BACK_IMAGE];
}
for (UIView* v in cell.subviews) {
if ([v isKindOfClass:[CatalogeView class]]) {
[v removeFromSuperview];
}
}
if (isLandscape) {
if (IPADAPP) {
[bgImage setFrame:CGRectMake(0, 0, 1024, 250)];
[bgImage setImage:[ImgUtil image:#"polka_gor#2x.png"]];
int num = 0;
for(int i = indexPath.row*CATALOGE_ON_SHELF_HORIZONTAL; i < [cataloges count] && i < (indexPath.row + 1)*CATALOGE_ON_SHELF_HORIZONTAL; i++){
CatalogeView* catalogeView = [cataloges objectAtIndex:i];
[catalogeView setPosition:CGPointMake(40 + 120*(num%CATALOGE_ON_SHELF_HORIZONTAL) * 2 , 30)];
[cell addSubview:catalogeView];
num++;
}
}else{
[bgImage setFrame:CGRectMake(0, 0, 480, 125)];
[bgImage setImage:[ImgUtil image:#"polka_gor.png"]];
int num = 0;
for(int i = indexPath.row*CATALOGE_ON_SHELF_HORIZONTAL; i < [cataloges count] && i < (indexPath.row + 1)*CATALOGE_ON_SHELF_HORIZONTAL; i++){
CatalogeView* catalogeView = [cataloges objectAtIndex:i];
[catalogeView setPosition:CGPointMake(20 + 120*(num%CATALOGE_ON_SHELF_HORIZONTAL),15)];
[cell addSubview:catalogeView];
num++;
}
}
}else {
if (IPADAPP) {
[bgImage setFrame:CGRectMake(0, 0, 768, 250)];
[bgImage setImage:[ImgUtil image:#"polka#2x.png"]];
int num = 0;
for(int i = indexPath.row*CATALOGE_ON_SHELF_VERTICAL; i < [cataloges count] && i < (indexPath.row + 1)*CATALOGE_ON_SHELF_VERTICAL; i++){
CatalogeView* catalogeView = [cataloges objectAtIndex:i];
[catalogeView setPosition:CGPointMake(20 + 105*(num%CATALOGE_ON_SHELF_VERTICAL) * 2.5 ,30)];
[cell addSubview:catalogeView];
num++;
}
}else{
[bgImage setFrame:CGRectMake(0, 0, 320, 125)];
[bgImage setImage:[ImgUtil image:#"polka.png"]];
int num = 0;
for(int i = indexPath.row*CATALOGE_ON_SHELF_VERTICAL; i < [cataloges count] && i < (indexPath.row + 1)*CATALOGE_ON_SHELF_VERTICAL; i++){
CatalogeView* catalogeView = [cataloges objectAtIndex:i];
[catalogeView setPosition:CGPointMake(10 + 105*(num%CATALOGE_ON_SHELF_VERTICAL),15)];
[cell addSubview:catalogeView];
num++;
}
}
}
return cell;
}
and the Catalogue View class:
#implementation CatalogeView
#synthesize delegate;
#synthesize cataloge;
- (void)dealloc {
[cataloge release];
[image release];
[title release];
[button release];
[super dealloc];
}
+(id) make{
NSInteger koef = 1;
if (IPADAPP) {
koef = 2;
}
CatalogeView* ctrl = [[[CatalogeView alloc] initWithFrame:CGRectMake(0, 0, FULL_VIEW_WIDTH * koef, FULL_VIEW_HEIGTH * koef)] autorelease];
[ctrl addAllSubviews];
return ctrl;
}
-(void) addAllSubviews{
NSInteger koef = 1;
if (IPADAPP) {
koef = 2;
}
if (!title) {
title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, FULL_VIEW_WIDTH * koef, TITLE_HEIGTH * koef)];
[title setNumberOfLines:2];
[title setTextColor:[UIColor whiteColor]];
[title setFont:[UIFont fontWithName:#"Helvetica" size:9 * koef]];
[title setTextAlignment:UITextAlignmentCenter];
[title setBackgroundColor:[UIColor clearColor]];
[self addSubview:title];
}
if (!image) {
image = [[UIImageView alloc] initWithFrame:CGRectMake(0, TITLE_HEIGTH * koef, FULL_VIEW_WIDTH * koef, IMAGE_HEIGTH * koef)];
[image setBackgroundColor:[UIColor clearColor]];
[self addSubview:image ];
}
if (!button) {
button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, FULL_VIEW_WIDTH * koef, FULL_VIEW_HEIGTH * koef)];
[button addTarget:self action:#selector(click) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button ];
}
}
-(void) addCatalogeInView:(CatalogeDbo*) newCataloge{
self.cataloge = newCataloge;
[title setText:cataloge.realName];
[image setImage:[DownloadImage getImageWithName:[NSString stringWithFormat:#"%#.png", cataloge.image]]];
}
-(void) setPosition:(CGPoint) position{
NSInteger koef = 1;
if (IPADAPP) {
koef = 2;
}
[self setFrame:CGRectMake(position.x, position.y, FULL_VIEW_WIDTH * koef, FULL_VIEW_HEIGTH * koef)];
}
-(void) click{
if(cataloge){
[delegate clGoInCataloge:cataloge];
}
}
#end
Your cell height was not matching with the subviews contentsize you are adding in cellForRowAtIndexPath method.
Also you should use unique Identifier for each row. Otherwise the already created cell with the same Identifier "landscape-cell" was re-used and not created again .
Use the Identifier something like
[NSString stringWithformat: "cell_%d",indexpath.row];
Hope you achieve the target.
Reading all this, my assumption is that you're adding CatalogeView multiple times and this causes the labels, buttons and images to overlap (the last two you just don't see overlapping) everytime a cell is dequeued. Instead, make a function that changes the values for the objects in CatalogeView and set them if it's already been added.
You're creating new ui elements dynamically every time that the cell's will be generated. Why don't you just create a custom cell (or two, landscape and portrait) inside a new nib file. This way you can access the elements you want and the labels won't overlap because you just can set them to the position you want, inside the InterfaceBuilder. And you just would need to call them like :
[cell.label1 setText
[cell.label2 setText....
And keep in mind, adding additional SubViews to UITableViewCells might cause a problem. You should keep the number of subviews as low as possible so the UITableView doesn't get to slow. There is a good explanation in a WWDC Stream:
iOS App Performance: Graphics and Animations
You might be calculating incorrectly your frames. For Landscape or portrait mode
if You are using a custum cell then you have to define height for row,and if you are using addsubview of cell then you have to provide correct positions of all subviews.
Seems that heightForRowAtIndexPath(or xib setting) returns different height than your CatalogueView which causes such overlapping. Also why not use UICollectionView(or PSTCollectionView in case you need to support iOS 5.x)?
! Вовка в Простоквашино и Дюймовочка блудного попугая - можно новые мультфильмы снимать. :)
(Some talking about Russian cartoons caused by overlapping names)
write below if you still face problem
cell=nil; // use this to create new cell
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:
}

Multiple TableViews in one View - Array of data sources?

I'm trying to recreate a view controller similar to the "weather" app that comes stock on the iPhone. I've got a scrollview that contains an individual tableview per page, and I'm struggling to figure out a way to specify the data for each table view.
The tricky part is that the info in each tableview and the tableviews themselves change based on user defaults. Basically, I have an Array of dictionaries stored in user defaults, and each object in this array has its own tableview. Each dictionary contains a title, a lat and a long. When I create the tables, I also use the lat and long to get some data from the internet via an api call and parser. Here's the code:
- (void)setupScrollView
{
scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor clearColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
//this is an array of dictionaries that hold a location title, as well as a lat and lng.
NSArray *arrayForLocations = [NSArray arrayWithArray:[appDelegate.defaults objectForKey:#"arrayOfLocationDicts"]];
NSLog(#"Array of Location Dicts holds: %#",arrayForLocations);
for (int i = 0; i < arrayForLocations.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
[self.scrollView addSubview:subview];
UITableView *tbView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, scrollView.frame.size.width, scrollView.frame.size.height - 40)];
tbView.backgroundColor = [UIColor grayColor];
tbView.tag = i;
tbView.delegate = self;
tbView.dataSource = self;
[subview addSubview:tbView];
UILabel *locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 260, 40)];
locationLabel.textColor = [UIColor blackColor];
locationLabel.text = [[arrayForLocations objectAtIndex:i]objectForKey:#"location_address"];
[subview addSubview:locationLabel];
pageControl.numberOfPages = [arrayForLocations count];
//get coordinate from dictionary
CLLocationCoordinate2D eventCoordinate;
eventCoordinate.latitude = [[[arrayForLocations objectAtIndex:i]objectForKey:#"location_latitude"]floatValue];
eventCoordinate.longitude = [[[arrayForLocations objectAtIndex:i]objectForKey:#"location_longitude"]floatValue];
//turn coordinate into data
SDJConnection *connection = [[SDJConnection alloc]init];
NSMutableArray *singleDataSource = [connection getEventInfoWithCoordinate:eventCoordinate];
//store data in array
[arrayOfDataSources addObject:singleDataSource];
NSLog(#"array of Data Sources in the scrollsetup: %#",arrayOfDataSources);
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * arrayForLocations.count, self.scrollView.frame.size.height);
}
So now my problem is telling each of these tables what data to display. My first thought was to set the tag of the table, as I do above, and then have something like this in the cellForRowAtIndexPath -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int i = tableView.tag;
if (tableView.tag = i) {
cell.textLabel.text = [[[arrayOfDataSources objectAtIndex:i]objectAtIndex:indexPath.row]eventTitle];
}
that unfortunately hasn't been working for me correctly. Does anyone have any thoughts as to how to get this done?
Thanks!!
For sure
if (tableView.tag = i) {
should be
if (tableView.tag == i) {
and even then, it's an odd construct -- not sure what you're trying to achieve there. You set the i to the tag and then you check to see if the tag is i? Doesn't really make sense -- that's where I'd suggest you take a close look and rethink your logic.

Resources