I have tableView and in one of the rows I have a horizontal scrollView and some images(images are in different view of the row), In horizontal scrollView i have added few buttons (10 buttons). when user clicks on any button from scrollView I call reloadData. Because I call reloadData so horizontal scrollView reloads again with new image Data. Now I want if user scrolls to end and clicked the last button from the scrollView, user should be able to see that selected button not the first one. I don't know how can i use scrollRectToVisible:animated to make this happen.
here is my code for scrollView and adding buttons on it.
-(void)addColorFiltersOnView:(UIView *)colorView{
if (_colorFilterView) {
[_colorFilterView removeFromSuperview];
}
self.colorFilterView = [[UIScrollView alloc] initWithFrame:colorView.bounds];
[_colorFilterView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[_colorFilterView setBackgroundColor:samergb(238)];
[_colorFilterView setShowsHorizontalScrollIndicator:NO];
int addedCount = 0;
int i=0;
CGFloat x = 10, y = 5;
if ([_colorFilters count] < 1) {
return;
}
for (i=0; i<[_colorFilters count] - 1; i++) {
id item = [_colorFilters objectAtIndex:i];
if ([item isKindOfClass:[NSString class]]){
if ([self.prodVIPDictionary.PDcolor isEqualToString:(NSString*)item] && i != 0) {
continue;
}
NSInteger itemsCount = [[_colorFilters objectAtIndex:i+1] integerValue];
if (itemsCount <= 0) {
break;
}
TTTAttributedLabel *itemLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
[itemLabel setNumberOfLines:1];
[itemLabel setTextAlignment:NSTextAlignmentCenter];
[itemLabel setFont:[UIFont systemFontOfSize:14]];
if ([_selectedColor isEqualToString:(NSString*)item])
[itemLabel setTextColor:[UIColor whiteColor]];
[itemLabel setText:[(NSString*)item capitalizedString]];
[itemLabel setBackgroundColor:samergb(255)];
itemLabel.layer.borderWidth = 1;
itemLabel.layer.masksToBounds = YES;
itemLabel.layer.cornerRadius = 10;
itemLabel.layer.borderColor = samergb(210).CGColor;
[itemLabel sizeToFit];
[_colorFilterView addSubview:itemLabel];
CGRect itemFrame = itemLabel.frame;
itemFrame.size.width += 20;
[itemLabel setFrame:itemFrame];
UIButton *optionBtn = [[UIButton alloc] initWithFrame:CGRectMake(x, y, itemLabel.frame.size.width + 6, 26)];
[optionBtn setTag:[_colorFilters indexOfObject:item]];
[optionBtn addTarget:self action:#selector(optionColorClicked:) forControlEvents:UIControlEventTouchUpInside];
[_colorFilterView addSubview:optionBtn];
[itemLabel setFrame:optionBtn.frame];
if ([_selectedColor isEqualToString:(NSString*)item]) {
[optionBtn setEnabled:NO];
[itemLabel setBackgroundColor:[LRUtils lrGreenColor]];
}
addedCount ++;
x += optionBtn.frame.size.width+5;
if (addedCount >= 20) {
break;
}
}else{
continue;
}
}
[_colorFilterView setContentSize:CGSizeMake((x + 10),colorView.frame.size.height)];
[colorView addSubview:_colorFilterView];
}
Instead of calling reloadData, you could call this method on the Table View:
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
You would need to create an NSArray containing all of the IndexPaths in the Table View except for the row with the scroll view and buttons. This way, the scroll view wouldn't get reset.
Related
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
created 4x4 metrics button in UITableView.
I want to select the button in sequentially order.
// button Creation in cell for row Index
for (int i = 0; i< [buttonArray count]; i++)
{
int buttonSpace = 10 * i + 10;
NSLog(#"ButtonPosition:%d",buttonSpace + (i * 50));
cell.Button = [[CustomButton alloc] initWithFrame:CGRectMake(buttonSpace + (i * 50),35, 50, 50)];
cell.Button.layer.cornerRadius = 25;
[cell.Button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
cell.Button.buttonIndex = i;
[cell.ScrollView addSubview:cell.Button];
cell.ScrollView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.3];
}
rowIndexValue = indexPath.row;
// Button action in view controller.
-(void)buttonAction:(CustomButton *)sender
{
if (rowIndexValue) {
int counter = (int)[sender buttonIndex];
if (counter == incrementValue)
{
sender.backgroundColor = [UIColor redColor];
counter += 1;
incrementValue = counter;
}
else{
sender.selected = NO;
}
}
}
The order of button action in sequential order, for any random row's.
user select 3rd row but selection row in third row start from 1st button then 2nd button then 3rd button finally 4th button.
4x4 - > 4 row for UITableview 4 button in each row. Once button is click it will be in disable Mode
Set proper value so that you can recognise button column as well as row position. buttonIndex is just saving i value so you will only get column position.You may set button.tag=indexPath.row and use it in the buttonAction method to know the row position.
Declare NSInteger tagValue globally in your viewController.
-(NSUInteger)getRowByBtn:(UIButton *)btn :(UITableView *)tblView
{
CGPoint center= btn.center;
CGPoint rootViewPoint = [btn.superview convertPoint:center toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:rootViewPoint];
NSLog(#"indexPath = %ld", (long)indexPath.row);
return indexPath.row;
}
With the help of above method you can get indexpath.row value from which you can determine the button for each row in the tableview.
[cell.Button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
-(void)buttonAction:(UIButton*)sender
{
UIButton *btn=(UIButton *)sender;
tagValue = [self getRowByBtn:btn :yourTableview];
[[self.view viewWithTag:tagValue]setUserInteractionEnabled:YES];
//or any other action
}
Set UIButton tag in CellForRowAtIndexPath
Like this :
[cell.btn_name addTarget:self action:#selector(onclick_button:) forControlEvents:UIControlEventTouchUpInside];
self.btn_name.tag=indexpath.row;
And
-(IBAction)onclick_button:(id)sender
{
int btn_index= ((UIView*)sender).tag;
NSLog(#"Btn index:%d",btn_index);
}
It fix the problem with below code.
-(void)buttonAction:(UIButton*)sender{
CGPoint center = sender.center;
CGPoint rootViewPoint = [sender.superview convertPoint:centre toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
sender.userInteractionEnabled = NO;
sender.backgroundColor = [UIColor redColor];
CustomButton *enableNextButton = (CustomButton *) [[self.goalsTableView cellForRowAtIndexPath:indexPath] viewWithTag:sender.tag+1];
enableNextButton.userInteractionEnabled = YES;
}
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;
}
Hi my requirement is showing image in scrollview along with that it should display next and previous button.User can scroll the image as well as use buttons to move images.
I have doubt about how to get the index/tag/imagename or anything else when user scroll based on that values buttons should be updated.
Here is my Code
[self arrayInitiaisation];
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical = NO;
scrollview.alwaysBounceHorizontal = YES;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"image%d",i+1]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag = i;
...
Array Initialisation method
-(void) arrayInitialisation {
count=0;
[super viewDidLoad];
images=[NSMutableArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
Action Methods
- (IBAction)nextButton:(id)sender {}
- (IBAction)prevButton:(id)sender {}
scroll is working correctly but when user clicks on prev and next image is not updating on 'imageview'
Here is my updated code
int count=0;
- (void)viewDidLoad
{
[super viewDidLoad];
[self arrayInitialisation];
[scrollview setScrollEnabled:YES];
self.scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(30 , 30, 320, 412)];
self.scrollview.delegate=self;
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical=NO;
scrollview.alwaysBounceHorizontal=YES;
scrollview.showsHorizontalScrollIndicator=NO;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(xOrigin, 0, 320, 412)];
imageView.image = [images objectAtIndex:i];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag=i;
}
scrollview.contentSize = CGSizeMake(320*numberOfViews, 412);
scrollview.contentOffset = CGPointMake(0,0);
[self.view addSubview:self.scrollview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void) arrayInitialisation{
count=0;
[super viewDidLoad];
images=[NSArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
- (IBAction)nextButton:(id)sender {
if(count==0){
count++;
NSLog(#"Next Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
}
else{
[previous setEnabled:YES];
count++;
NSLog(#"Next Button : else Loop %d",count);
if(count <images.count){
[imageView setImage:[images objectAtIndex:count]];
}
else{
[next setEnabled:NO];
}
}
}
- (IBAction)prevButton:(id)sender {
if(count==0){
//count--;
NSLog(#"prev Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:NO];
[next setEnabled:YES];
}
else{
count--;
NSLog(#"prev Button : else Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
//[next setEnabled:YES];
}
}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate: (BOOL)decelerate{
//NSLog(#"scrollViewDidEndDragging");
/* count=count+1;
NSLog(#"scrollViewDidEndDragging : %d",count);*/
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//NSLog(#"scrollViewDidScroll");
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0){
//NSLog(#"scrollViewWillEndDragging");
count=count+1;
NSLog(#"scrollViewWillEndDragging : %d",count);
}
I have left and right button for scroll images, and imageview width is same.
I am writing code for scroll image at pressing button.
int pos=0;// ViewDiaLoad
- (IBAction)OnClickLeftButton:(UIButton*)sender
{
if(pos>0)
{
pos -=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
- (IBAction)OnClickRightButton:(UIButton*)sender
{
if(pos<numberOfImages)
{
pos +=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
Set scrollView Deleagte
Scroll View delegate Method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pos=scrollView.contentOffset.x/scrollView.frame.size.width;
}
You can use UIPageControl and set and get image according to page index. For more information check out this link
Try below piece of code. I hope it will help. Put this in your .h file
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
NSMutableArray *arrImages;
NSInteger page;
Now in your - (void)viewDidLoad put following lines.
int x = 30;
for (int i=0; i< arrImages.count; i++)
{
UIImageView *imgShow = [[UIImageView alloc]initWithFrame:CGRectMake(x+20, 50, self.view.frame.size.width-100, self.view.frame.size.height-180)];
imgShow.backgroundColor = [UIColor whiteColor];
imgShow.image = [UIImage imageNamed:[arrImages objectAtIndex:i]];
imgShow.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview:imgShow];
x = x+scrollView.frame.size.width;
}
scrollView.contentSize = CGSizeMake(5*self.view.frame.size.width, 0);
pageControl.backgroundColor = [UIColor clearColor];
pageControl.pageIndicatorTintColor = [UIColor grayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
[pageControl setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];
pageControl.numberOfPages = arrTitle.count;
pageControl.currentPage = 0;
implement scroll view delegate.
#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
CGFloat pageWidth = scrollView.frame.size.width;
float fractionalPage = scrollView.contentOffset.x / pageWidth;
page = lround(fractionalPage);
pageControl.currentPage = page;
}
- (IBAction)prevButton:(UIButton *)sender
{
page = page-1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
- (IBAction)nextButton:(UIButton *)sender
{
page = page+1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
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:
}