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.
Related
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?
Can anyone help me ? I want to create dynamic text field in side a loop.I have been able to create and made it editable too. My requirements are in below.
i.I want to access each text fields value and make a sum of those will store in a Label.
ii. Let's say there are 5 dynamic created text fields having value (10,20,30,40,50).
so label displays sum of 5 value. ie. 10+20+30+40+50 = 150
if i make changes in either textfield values, it should recalculate and changes the total sum in label.
my logic goes as below.
-(void)create
{
myarr = [NSMutableArray arrayWithObjects:#"1000",#"2000",#"3000",#"4000",#"5000", nil];
int x = 20, y = 50;
int width = 280, height = 40;
for (int item=0; item<[myarr count]; item++)
{
edit_txt = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
edit_txt.text = [NSString stringWithFormat:#"%#",[myarr objectAtIndex:item]];
[edit_txt setTag:item+1];
edit_txt.placeholder = #"Click here to type";
edit_txt.borderStyle = UITextBorderStyleRoundedRect;
edit_txt.font = [UIFont systemFontOfSize:15];
edit_txt.textAlignment = NSTextAlignmentLeft;
edit_txt.returnKeyType = UIReturnKeyDefault;
edit_txt.delegate = (id)self;
[self.view addSubview:edit_txt];
y += height;
}
tot_txt = [[UITextField alloc]initWithFrame:CGRectMake(edit_txt.frame.origin.x, edit_txt.frame.origin.y + height + 10, width , height)];
tot_txt.placeholder = #"Total Value";
tot_txt.borderStyle = UITextBorderStyleRoundedRect;
tot_txt.font = [UIFont systemFontOfSize:15];
tot_txt.textAlignment = NSTextAlignmentLeft;
tot_txt.returnKeyType = UIReturnKeyDefault;
tot_txt.delegate = (id)self;
[self.view addSubview:tot_txt];
save_btn = [UIButton buttonWithType:UIButtonTypeCustom];
[save_btn setFrame:CGRectMake(tot_txt.frame.origin.x, tot_txt.frame.origin.y + height + 10, width , height)];
[save_btn setTitle:#"Save" forState:UIControlStateNormal];
[save_btn addTarget:self action:#selector(save_click:) forControlEvents:UIControlEventTouchUpInside];
[save_btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[self.view addSubview:save_btn];
CALayer *btnlayer = [save_btn layer];
[btnlayer setBorderColor:[UIColor redColor].CGColor];
[btnlayer setBorderWidth:0.3];
[btnlayer setCornerRadius:20.0];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
int count = 0;
for (int item = 0; item < [myarr count]; item++)
{
UITextField *textField = ([[self.view viewWithTag:item + 1] isKindOfClass:[UITextField class]])?(UITextField *)[self.view viewWithTag:item + 1]:nil;
count += [textField.text intValue];
}
tot_txt.text = [NSString stringWithFormat:#"%d", count];
}
Thanks in advance.
Ajeet Kumar.
It would be more easy,
To access each text field (the scope is available only within the loop),you can use tag property of the text field.
Example:
for (int itemIndex = 1; itemIndex <= 5; itemIndex++)
{
UITextField *textField = [[UITextField alloc] initWithFrame:yourFrame];
//all properties assigning here
textField.tag = itemIndex; //assigning tag here(starts from 1).
textField.delegate = self;
[self.view addSubview: textField];
}
Now, here comes the calculation. Implement the UITextField delegates.
Write the <UITextFieldDelegate> in your .h file
#interface yourClassName : UIViewController <UITextFieldDelegate>
To calculate while end editing,
-(void)textFieldDidEndEditing:(UITextField *)textField
{
int count = 0;
for (int itemIndex = 1; itemIndex <= 5; itemIndex++)
{
UITextField *textField = ([[self.view viewWithTag:itemIndex] isKindOfClass:[UITextField class]])?(UITextField *)[self.view viewWithTag:itemIndex]:nil;
count += [textField.text intValue];
}
countLabel.text = [NSString stringWithFormat:#"%d", count];
}
To calculate while editing, implement delegate shouldChangeCharactersInRange and use the same code base.
Also implement the delegates textFieldShouldClear ,
textFieldShouldReturn and use the same code base.
Please make sure that, your view not holding any elements with the tag from 1 to 5 except these test fields.
Also, you can avoid the looping by applying your thoughts on it ;)
I did like this,
#import "ViewController.h"
#interface ViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate> {
UITableView* _tableView;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, 768, 600) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"SomeCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"SomeCell"];
UITextField* _textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 600, 40)];
_textField.delegate = self;
_textField.tag = indexPath.row + 1;
[_textField setBackgroundColor:[UIColor lightGrayColor]];
[_textField addTarget:self action:#selector(onTextChange:) forControlEvents:UIControlEventEditingChanged];
[cell.contentView addSubview:_textField];
}
return cell;
}
- (void)onTextChange:(id)sender
{
double result = 0.0;
for (int itemIndex = 0; itemIndex < 5; itemIndex++) {
UITableViewCell* cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:itemIndex inSection:0]];
UITextField* fooTF = (UITextField*)[cell.contentView viewWithTag:itemIndex + 1];
result += [fooTF.text doubleValue];
}
// update your lable here
NSLog(#"result %f", result);
//for sample
self.title = [NSString stringWithFormat:#"%f", result];
}
- (float)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
return 50.0;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterNoStyle];
NSString* newString = [NSString stringWithFormat:#"%#%#", textField.text, string];
NSNumber* number = [nf numberFromString:newString];
//allow only numbers
if (number)
return YES;
else
return NO;
}
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;
}
}
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?
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:
}