I have a scroll view which consists of many of views. These views are placed in the view according to their dynamic size. There is also a delete button on each view which deletes the view from the scrollview, and replace the others accordingly.
But I have a problem, when I delete something scrollview does not stay where I deleted. One row up or down.
This is my deletion code:
-(void) redrawTheList:(id)sender :(NSString*) except{
int tempo = counterRow;
NSMutableDictionary *doctorTemp = [[NSMutableDictionary alloc]initWithDictionary:doctorAddition copyItems:YES];
for(int i = 0; i<=tempo;i++)
{
NSString *dictTempKey = [NSString stringWithFormat:#"row%d",i];
NSMutableArray * tempArray = [doctorTemp objectForKey:dictTempKey];
for(UIView * subview in tempArray)
{
for(UIView * subview2 in [subview subviews])
{
if([subview2 isKindOfClass:[UILabel class]])
{
if([((UILabel*)subview2).text isEqualToString:except])
{
counterRow = i;
tempile = i;
yAxis=5.0+(i*40.0);
}
}
}
}
}
for(int j=tempile;j<=tempo;j++)
{
NSString *dictTempKey2 = [NSString stringWithFormat:#"row%d",j];
NSMutableArray * tempArray = [doctorAddition objectForKey:dictTempKey2];
for(UIView * subview in tempArray)
{
[subview removeFromSuperview];
}
[doctorAddition removeObjectForKey:dictTempKey2];
}
for(int k=tempile;k<=tempo;k++)
{
NSString *dictTempKey3 = [NSString stringWithFormat:#"row%d",k];
NSMutableArray * tempArray2 = [doctorTemp objectForKey:dictTempKey3];
for(UIView * subview in tempArray2)
{
for(UIView * subview2 in [subview subviews])
{
if([subview2 isKindOfClass:[UILabel class]])
{
if(![((UILabel*)subview2).text isEqualToString:except])
{
[self createDoctorBox:((UILabel*)subview2).text];
}
}
}
}
}
}
CreateDoctorBox method;
-(UIView*)createDoctorBox : (NSString*)name {
[addedList addObject:name];
NSString *myString = name;
CGSize stringSize = [myString sizeWithFont:[UIFont fontWithName:#"Helvetica-Bold" size:13]];
UIView *doktorKutu = [[UIView alloc]init];
[doctorList addSubview:doktorKutu];
UIView *doktorKutuBas = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 18, 36)];
[doktorKutuBas setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"doktor_isim_kutu_bas"]]];
[doktorKutu addSubview:doktorKutuBas];
UILabel * doktorKutuGovde = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, stringSize.width+3, 36)];
[doktorKutuGovde setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[doktorKutuGovde setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"doktor_isim_kutu_1px"]]];
[doktorKutuGovde setUserInteractionEnabled:YES];
[doktorKutuGovde setText:myString];
[doktorKutu addSubview:doktorKutuGovde];
UIView * doktorKutuKic = [[UIView alloc]initWithFrame:CGRectMake(stringSize.width+13, 0, 18, 36)];
[doktorKutuKic setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"doktor_isim_kutu_kic"]]];
[doktorKutu addSubview:doktorKutuKic];
UIImageView *cancelImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"cikar"]];
cancelImage.frame = CGRectMake(-5,9, 18, 18);
[doktorKutuKic addSubview:cancelImage];
UIButton *cancel = [[UIButton alloc]initWithFrame:CGRectMake(-5,0, 20, 36)];
[cancel setUserInteractionEnabled:YES];
[cancel addTarget:self action:#selector(removeNameFromTheList:) forControlEvents:UIControlEventTouchUpInside];
[doktorKutuKic addSubview:cancel];
UITapGestureRecognizer *singlePress =[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSinglePress:)];
[doktorKutuGovde addGestureRecognizer:singlePress];
[doktorKutu bringSubviewToFront:cancel];
[doctorCommented addObject:doktorKutu];
[doktorKutuKic bringSubviewToFront:cancel];
[doktorKutu bringSubviewToFront:cancel];
dictRowKey = [NSString stringWithFormat:#"row%d",counterRow];
NSMutableArray *row = [[NSMutableArray alloc]init];
doktorKutu.frame = CGRectMake(5, yAxis, stringSize.width+30, 36);
if([doctorAddition objectForKey:dictRowKey]!=nil)
{
row = (NSMutableArray*)[doctorAddition objectForKey:dictRowKey];
if(row.count>0)
{
int totalWidth = 5;
for(int i=0;i<row.count;i++)
{
totalWidth = totalWidth + ((UIView*)[row objectAtIndex:i]).frame.size.width+5;
}
if(totalWidth+stringSize.width<520)
{
doktorKutu.frame = CGRectMake(totalWidth, yAxis, stringSize.width+30, 36);
[row addObject:doktorKutu];
[doctorAddition removeObjectForKey:dictRowKey];
[doctorAddition setObject:row forKey:dictRowKey];
}
else
{
doktorKutu.frame = CGRectMake(5, yAxis+40, stringSize.width+30, 36);
yAxis= yAxis + 40.0;
counterRow++;
dictRowKey = [NSString stringWithFormat:#"row%d",counterRow];
row = [[NSMutableArray alloc]init];
[row addObject:doktorKutu];
[doctorAddition setObject:row forKey:dictRowKey];
}
}
}
else
{
[row addObject:doktorKutu];
[doctorAddition setObject:row forKey:dictRowKey];
}
[doctorList setContentSize:CGSizeMake(10, 36+(counterRow*41))];
return doktorKutu;
}
its because when your function " createDoctorBox " call, there may be you have changed a scrollview properties. Please check there.
in your code [doctorList setContentSize:CGSizeMake(10, 36+(counterRow*41))]; its reset the contentOffset of the UIScrollView. if you want to stay on position of delete button, then below that line, set the delete button point as contentOffset of UIScrollView.
Example code:
[doctorList setContentSize:CGSizeMake(10, 36+(counterRow*41))];
doctorList.contentOffset:CGMakePoint(0,deleteBtn.frame.origin.y);
if its help then please vote for me.
Related
Here i mention the code what i wrote , In UITableViewHeaderFooterView while scrolling and second time that method is calling text was overlapping (How many time scrolling that much time text are adding), Here i mention the Screen shots : http://prntscr.com/9sgq7x
_imgViewUser.imageURL = [NSURL URLWithString:modelData.user_image_big];
_lblUserName.text = modelData.posted_by;
_lblTime.text = modelData.posted_time;
if ([modelData.commentArray count])
{
_imgViewUser.imageURL = [NSURL URLWithString:[[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_user_small"]];
NSString *nameStr = #"";
if ([GETVALUE(kUSERID) isEqualToString:[[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_userid"]]) {
nameStr = #"You";
}else {
nameStr = [[modelData.commentArray objectAtIndex:0] valueForKey:#"full_name"];
}
_lblUserName.text = nameStr;
_lblTime.text = [[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_post_time"];
}
NSString *OriginalFrontendText = [[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_text"];
UIFont *font = [UIFont fontWithName:#"Arial" size:13.0];
CGFloat descriptionHeight = [OriginalFrontendText boundingRectWithSize:CGSizeMake(180, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName: font} context:nil].size.height;
[[self viewWithTag:tag]removeFromSuperview];
STTweetUserName *commentLbl;
if ([modelData.comments_count intValue] > 1) {
commentLbl = [[STTweetUserName alloc]initWithFrame:CGRectMake(0, 39, self.frame.size.width-10, descriptionHeight) withFont:9.0 attributeTextColor:[UIColor darkGrayColor] name:#"See More"];
commentLbl.text = [NSString stringWithFormat:#"%#See More",[[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_text"]];
}else
{
commentLbl = [[STTweetUserName alloc]initWithFrame:CGRectMake(0, 39, self.frame.size.width-10, descriptionHeight) withFont:9.0 attributeTextColor:[UIColor darkGrayColor] name:nil];
commentLbl.text = [[modelData.commentArray objectAtIndex:0] valueForKey:#"cmt_text"];
}
commentLbl.tag = tag;
if (commentLbl.tag == tag) {
[commentLbl removeFromSuperview];
}
[self addSubview:commentLbl];
commentLbl.detectionBlock = ^(STTweetHotUserName hotWord, NSString *string, NSString *protocol, NSRange range){
showAlert(string, nil, #"OK", nil);
//[self SeeMoreClicked];
};
self.frame = CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, self.contentView.frame.size.width, 150);
i am getting overlopping while scrolling
Use following code to make your footer view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIView * v = [[UIView alloc] init];
v.frame = CGRectMake(0, 0, tableView.frame.size.width, 44);
UILabel * label = [[UILabel alloc] init];
label.frame = CGRectMake(20, 0, tableView.frame.size.width/2, 44);
label.text = #"Some text";
[v addSubview:label];
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(label.frame.size.width+label.frame.origin.x, 0, tableView.frame.size.width/2, 44);
[btn addTarget:self action:#selector(seeMore) forControlEvents:UIControlEventTouchUpInside];
btn.titleLabel.text = #"See more";
[v addSubview:btn];
return v;
}
Customise the above code however you want. This won't let your footer view overlap with text.
Get width of NSString text using
- (CGSize)getHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+20.0f);
}
return size;
}
I am creating a class, that creates an option bar with multiple scroll views accessible by buttons.
This is how I add the subview with its content:
NSArray *scroll1 = [NSArray arrayWithObjects:#"normal",#"tiltshift",#"zoom",#"normal",#"blur",#"outline",#"coming soon", nil];
NSArray *scroll2 = [NSArray arrayWithObjects:#"Emoji Natur-01",#"Emoji Natur-02",#"Emoji Natur-03",#"Emoji Natur-04",#"Emoji Natur-05",#"Emoji Natur-06",#"Emoji Natur-07",#"Emoji Natur-08",#"Emoji Natur-09",#"Emoji Natur-10",#"Emoji Natur-11",#"Emoji Natur-12", nil];
NSArray *scroll3 = [NSArray arrayWithObjects:#"Linear",#"Parallel",#"Parallel 2",#"Crescendo",#"Dubstep",#"Blackhole",#"coming soon", nil];
NSArray *content = [NSArray arrayWithObjects:scroll1,scroll2,scroll3, nil];
[self.view addSubview:[self.bottomOptionView initWithFrame:self.view.frame withContent:content]];
The Subclass then generate a scrollview for each Array, with the buttons based on the content of the array:
-(void)addScrollViewOfContent:(NSArray*)array{
int viewNumber = array.count;
for (int i = 0 ; i < viewNumber; i++) {
//create the main buttons
NSArray *content = array[i];
UIButton *buttonAccess = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat buttonEdge = 40;
CGFloat buttonSpace = self.frame.size.width /viewNumber;
int placeOfButton = i+1;
CGFloat buttonAnchor = ((placeOfButton*(buttonSpace)) - (buttonSpace /2+ buttonEdge/2));
buttonAccess.frame = CGRectMake(buttonAnchor, 0 , buttonEdge, buttonEdge);
[buttonAccess setBackgroundColor:[UIColor redColor]];
buttonAccess.tag = i;
[buttonAccess addTarget:self action:#selector(buttonAccess:) forControlEvents:UIControlEventTouchDown];
[self addSubview:buttonAccess];
UIScrollView *ScrollView = [[UIScrollView alloc]init];
ScrollView.frame = CGRectMake(0, 50, self.frame.size.width, self.frame.size.height);
ScrollView.showsHorizontalScrollIndicator = YES;
ScrollView.tag = i;
ScrollView.backgroundColor =[UIColor colorWithRed:0 green:0.0 blue:0.0 alpha:0.0];
ScrollView.indicatorStyle = UIScrollViewDecelerationRateNormal ;
//UIImageView *selector = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"FILTER_SELECT.png"]];
CGFloat btnX = 0;
for (int i = 0 ; i < content.count; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(btnX, 2 , 65, 65);
UIImage *img = [UIImage imageNamed:[content objectAtIndex:i]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(subButtonTarget:) forControlEvents:UIControlEventTouchDown];
button.tag = i;
[button setTitle:[content objectAtIndex:i] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"MyriadPro-Cond" size:15];
button.titleLabel.textColor = [UIColor whiteColor];
button.titleLabel.textAlignment = UIBaselineAdjustmentAlignBaselines ;
button.showsTouchWhenHighlighted = YES;
[ScrollView addSubview:button];
btnX = btnX + 100;
}
btnX = btnX - 80;
ScrollView.contentSize = CGSizeMake(btnX + 50, 80);
ScrollView.hidden = YES;
[self.scrollViewArray addObject:ScrollView];
[self addSubview:ScrollView];
}
This gives me exactly what I want.
Then I detect which button, of which scroll view is pressed to trigger the action.
-(void)subButtonTarget:(UIButton *)sender{
int button = sender.tag;
int scrollview = self.selectedScrollView;
[self.videoEditor subAction:button ofScrollView:scrollview];
}
-(void)buttonAccess:(UIButton *)sender{
// self.selectedScrollView = sender.tag;
for (int i=0; i< self.scrollViewArray.count; i++) {
UIScrollView *scrollview= [self.scrollViewArray objectAtIndex:i];
scrollview.hidden= YES;
}
int scrollIndex = sender.tag;
UIScrollView *scrollview= [self.scrollViewArray objectAtIndex:scrollIndex];
scrollview.hidden = NO;
}
Basically when one of the button is touched, it calls a function in the view controller in which the sublclass was initially called.
The problem is that, on touchevent nothing happens, except for NSLog. Would that be because of the dependency relation of the subClass and the VC that uses it?
You should set this one for each UIScrollView
ScrollView.delaysContentTouches = NO;
And try to subclass UIScrollView with override method
-(BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
All my labels, done button and back button are scrolling within my icarousel. Is there a way to stop them from moving with the swipe gesture or are they inherently fixed? Or is it a case of taking them out of the function all together?
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
GalleryImage* gi = [self.galleryItem.galleryImages objectAtIndex:index];
UIImageView* imageView = nil;
UILabel* positionLabel = nil;
//UILabel* titleLabel = nil;
UILabel* label = nil;
UIButton* doneButton = nil;
UIView* labelBackground = nil;
UIActivityIndicatorView * spinnerView = nil;
UILabel * errorMessage = nil;
UILabel* titleLabel = nil;
//create new view if no view is available for recycling
if (view == nil) {
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.carousel.frame.size.width, self.carousel.frame.size.height)] ;
// Image
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.carousel.frame.size.width, self.carousel.frame.size.height)] ;
imageView.contentMode = UIViewContentModeScaleAspectFit;// UIViewContentModeCenter;
imageView.tag = 1;
// Spiner
spinnerView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinnerView setFrame:imageView.frame];
spinnerView.tag = 11;
//Error message
errorMessage = [[UILabel alloc] initWithFrame:spinnerView.frame];
[errorMessage setTextAlignment:NSTextAlignmentCenter];
[errorMessage setTextColor:[UIColor whiteColor]];
errorMessage.font = [UIFont fontWithName:#"Helvetica-Bold" size: 14.0];
errorMessage.tag = 111;
[imageView addSubview:errorMessage];
[imageView addSubview:spinnerView];
[view addSubview:imageView];
// Position
positionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.carousel.frame.size.width, 30)] ;
positionLabel.backgroundColor = [UIColor clearColor];
positionLabel.textAlignment = NSTextAlignmentCenter;
positionLabel.lineBreakMode = NSLineBreakByWordWrapping;
positionLabel.numberOfLines=1;
positionLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 14.0];
positionLabel.textColor = [UIColor whiteColor];
positionLabel.tag = 2;
//if(UIInterfaceOrientationPortrait == self.interfaceOrientation)
if(UIInterfaceOrientationIsPortrait(self.interfaceOrientation))
{
// Title
titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, self.carousel.frame.size.width - 20, 100)] ;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = NSTextAlignmentLeft;
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
titleLabel.numberOfLines = 4;
titleLabel.font = [UIFont fontWithName:#"Georgia" size: 18.0];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.text = [NSString stringWithFormat:#"%# \n", self.galleryItem.title];
[view addSubview:titleLabel];
/*
* Manage carousel speed and deceleration rate for portrait mode
*/
//self.carousel.decelerationRate = 0.175f;
//self.carousel.scrollSpeed = 0.45f;
}
else if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
{
/*
* Manage carousel speed and deceleration rate for landscape mode
*/
//self.carousel.decelerationRate = 0.25f;
//self.carousel.scrollSpeed = 0.55f;
}
labelBackground = [[UIView alloc] initWithFrame:CGRectMake(0, self.carousel.frame.size.height - 160, self.carousel.frame.size.width , 160)] ;
CAGradientLayer *labelBackgroundGradient = [CAGradientLayer layer];
labelBackgroundGradient.frame = labelBackground.bounds;
labelBackgroundGradient.colors = [NSArray arrayWithObjects: (id)[[UIColor clearColor]CGColor],
(id)[[UIColor blackColor]CGColor],
nil
];
[labelBackground.layer insertSublayer:labelBackgroundGradient atIndex:0];
labelBackground.opaque = false;
labelBackground.tag = 5;
// Description
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake( 0.0f,
0.0f,
labelBackground.bounds.size.width - 20.0f,
labelBackground.bounds.size.height)] ;
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentLeft;
label.numberOfLines = 0;
label.font = [label.font fontWithSize:12];
label.textColor = [UIColor whiteColor];
label.text = gi.descriptionGalleryImage;
[label autoAdjustGalleryCaptionSize];
[label setFrame:CGRectMake( label.bounds.origin.x + 10.0f,
label.bounds.origin.y + (labelBackground.bounds.size.height - (label.bounds.size.height + 10.0f)),
label.bounds.size.width,
label.bounds.size.height
)];
label.tag = 6;
[labelBackground addSubview:label];
[view addSubview:labelBackground];
} else {
imageView = (UIImageView *)[view viewWithTag:1];
spinnerView = (UIActivityIndicatorView*)[imageView viewWithTag:11];
errorMessage = (UILabel*) [imageView viewWithTag:111];
positionLabel = (UILabel *)[view viewWithTag:2];
doneButton = (UIButton *)[view viewWithTag:3];
//titleLabel = (UILabel *)[view viewWithTag:4];
labelBackground = (UIView *)[view viewWithTag:5];
label = (UILabel*)[view viewWithTag:6];
}
//Start image loading
ImageSize* imSize = [gi getLargestImage];
[spinnerView startAnimating];
errorMessage.text = #"";
[imageView sd_setImageWithURL:[NSURL URLWithString:imSize.source] placeholderImage:nil options:SDWebImageContinueInBackground progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//progress bar could be here
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//remove progressbar
[spinnerView stopAnimating];
//Display error message
if(error)
{
//errorMessage.text = error.localizedDescription;
errorMessage.text = #"Cannot load image";
}
//Assign image
if(image)
{
[imageView setImage:image];
}
}];
positionLabel.text = [NSString stringWithFormat:#"%d of %ld", (index + 1), (long)[self.galleryItem.galleryImages count]];
UIView* v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.carousel.frame.size.width, 30)];
v.backgroundColor = [UIColor blackColor];
v.alpha = 0.6;
[view addSubview:v];
[view addSubview:positionLabel];
// Done button
doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 0 , 50, 30);
[doneButton setImage:[UIImage imageNamed:#"back_button_white"] forState:UIControlStateNormal];
doneButton.imageEdgeInsets = UIEdgeInsetsMake(0,5,0,5);
[doneButton setTintColor:[UIColor whiteColor]];
[doneButton addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:doneButton];
/*
* The description. Why are we setting the frame for the label multiple times?
* We need to do this so it can autoadjust its size and position according
* to the text contained within it.
*/
[label setText:gi.descriptionGalleryImage];
[label autoAdjustGalleryCaptionSize];
[label setFrame:CGRectMake( label.bounds.origin.x + 10.0f,
label.bounds.origin.y + (labelBackground.bounds.size.height - (label.bounds.size.height + 10.0f)),
label.bounds.size.width,
label.bounds.size.height
)];
labelBackground.hidden = self.hideLandscapeDetails;
label.hidden = self.hideLandscapeDetails;
doneButton.hidden = self.hideLandscapeDetails;
positionLabel.hidden = self.hideLandscapeDetails;
v.hidden =self.hideLandscapeDetails;
titleLabel.hidden = self.hideLandscapeDetails;
self.tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showHideInfo:)];
[view addGestureRecognizer:self.tap1];
// scroll portrait view to same index
if (self.delegate) {
[self.delegate setReturnIndex:self.carousel.currentItemIndex];
}
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:#"Image Gallery" // Event category (required)
action:#"Gallery Image Viewed" // Event action (required)
label:#"Picture swipe" // Event label
value:[NSNumber numberWithLong:(index + 1)]] build]]; // Event value
return view;
}
The label should be above the iCarousel to do what you want, not inside the views of the carousel.
For testing purpose I have create project where I have two scrollview. First scrollview have images that I inserted manually and in second scrollview I have list of buttons (as menu).
I have button as right and left to scroll UIScrollView programmatically.
After clicking this button I was moving scrollview by setting content size.
myCounter.text = [NSString stringWithFormat:#"%d", [myCounter.text intValue] - 1];
CGRect page = CGRectMake(320*([myCounter.text intValue] ), 230, 320, 150);
[myScrollView scrollRectToVisible:page animated:YES];
CGRect page2 = CGRectMake(320*([myCounter.text intValue] ), 20, 320, 200);
[firstScrollView scrollRectToVisible:page2 animated:YES];
The problem I am facing is only first scroll view is getting scrolled but not the second one.
I am really confused why this is happening.
I am also attaching same project at dropbox as code is little more.
Project at dropbox
Full Code if some one don't want to download project
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIScrollView *myScrollView;
#property (weak, nonatomic) IBOutlet UILabel *myCounter;
#property (weak, nonatomic) IBOutlet UIScrollView *firstScrollView;
- (IBAction)goToLeft:(id)sender;
- (IBAction)goToRight:(id)sender;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myScrollView, myCounter, firstScrollView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
firstScrollView.contentSize = CGSizeMake(800, 200);
myCounter.text = #"0";
}
- (void) viewDidAppear:(BOOL)animated {
for (int j = 0; j < 2; j++) {
NSString *bname = #"";
int x = 20;
for (int i = 0; i < 8; i++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 66, 75)];
UIButton *rightArrowButton;
UIButton *leftArrowButton;
leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(x-38, 49, 26, 52)];
if (i==2) {
rightArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(294, 49, 26, 52)];
leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(1, 49, 26, 52)];
} else if (i==5) {
rightArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(614, 49, 26, 52)];
leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(320, 49, 26, 52)];
} else if (i==7) {
rightArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(934, 49, 26, 52)];
leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(640, 49, 26, 52)];
} else {
rightArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(x+62, 49, 26, 52)];
leftArrowButton = [[UIButton alloc] initWithFrame:CGRectMake(x-38, 49, 26, 52)];
}
bname = #"";
if (i==0) {
bname = #"doctors_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = YES;
}
if (i==1) {
bname = #"all-offers_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = YES;
}
if (i==2) {
bname = #"hospitals_icon.png";
rightArrowButton.hidden = NO;
leftArrowButton.hidden = YES;
}
if (i==3) {
bname = #"ads_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = YES;
}
if (i==4) {
bname = #"alternative_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = YES;
}
if (i==5) {
bname = #"pharmacy_icon.png";
rightArrowButton.hidden = NO;
leftArrowButton.hidden = NO;
}
if (i==6) {
bname = #"equ_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = YES;
}
if (i==7) {
bname = #"supplies_icon.png";
rightArrowButton.hidden = YES;
leftArrowButton.hidden = NO;
}
UIImage *btnImage = [UIImage imageNamed:bname];
[button setImage:btnImage forState:UIControlStateNormal];
[button setTag:(i+1)];
[myScrollView addSubview:button];
btnImage = [UIImage imageNamed:#"r_arrow.png"];
[rightArrowButton setImage:btnImage forState:UIControlStateNormal];
[rightArrowButton setTag:998];
[rightArrowButton addTarget:self action:#selector(goToRight:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:rightArrowButton];
btnImage = [UIImage imageNamed:#"l_arrow.png"];
[leftArrowButton setImage:btnImage forState:UIControlStateNormal];
[leftArrowButton setTag:999];
[leftArrowButton addTarget:self action:#selector(goToLeft:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:leftArrowButton];
UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(x, 76, 66, 75)];
if (i==0) {
bname = #"medical_icon.png";
}
if (i==1) {
bname = #"dental_icon.png";
}
if (i==2) {
bname = #"beauty_icon.png";
}
if (i==3) {
bname = #"labs_icon.png";
}
if (i==4) {
bname = #"magazine_icon.png";
}
if (i==5) {
bname = #"news_icon.png";
}
if (i<=5) {
btnImage = [UIImage imageNamed:bname];
[button2 setImage:btnImage forState:UIControlStateNormal];
[button2 setTag:(i+8+1)];
[myScrollView addSubview:button2];
}
x += button.frame.size.width + 40;
}
}
// myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(320*3, 150);
myScrollView.backgroundColor = [UIColor clearColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)goToLeft:(id)sender {
myCounter.text = [NSString stringWithFormat:#"%d", [myCounter.text intValue] - 1];
CGRect page = CGRectMake(320*([myCounter.text intValue] ), 230, 320, 150);
[myScrollView scrollRectToVisible:page animated:YES];
CGRect page2 = CGRectMake(320*([myCounter.text intValue] ), 20, 320, 200);
[firstScrollView scrollRectToVisible:page2 animated:YES];
NSLog(#"myCounter.text==%d", 320*([myCounter.text intValue]));
}
- (IBAction)goToRight:(id)sender {
myCounter.text = [NSString stringWithFormat:#"%d", [myCounter.text intValue] + 1];
CGRect page = CGRectMake(320*([myCounter.text intValue] ), 230, 320, 150);
[myScrollView scrollRectToVisible:page animated:YES];
CGRect page2 = CGRectMake(320*([myCounter.text intValue] ), 20, 320, 200);
[firstScrollView scrollRectToVisible:page2 animated:YES];
NSLog(#"myCounter.text==%d", 320*([myCounter.text intValue]));
}
#end
I have downloaded your code and modify the code below, your "page.origin.y is out of the contentSize.height"
- (IBAction)goToLeft:(id)sender {
myCounter.text = [NSString stringWithFormat:#"%d", [myCounter.text intValue] - 1];
CGRect page = CGRectMake(320*([myCounter.text intValue] ), 0, 320, 150);
[myScrollView scrollRectToVisible:page animated:YES];
CGRect page2 = CGRectMake(320*([myCounter.text intValue] ), 0, 320, 200);
[firstScrollView scrollRectToVisible:page2 animated:YES];
NSLog(#"myCounter.text==%d", 320*([myCounter.text intValue]));
}
- (IBAction)goToRight:(id)sender {
myCounter.text = [NSString stringWithFormat:#"%d", [myCounter.text intValue] + 1];
CGRect page = CGRectMake(320*([myCounter.text intValue] ), 0, 320, 150);
[myScrollView scrollRectToVisible:page animated:YES];
CGRect page2 = CGRectMake(320*([myCounter.text intValue] ), 0, 320, 200);
[firstScrollView scrollRectToVisible:page2 animated:YES];
NSLog(#"myCounter.text==%d", 320*([myCounter.text intValue]));
}
Hey mate please set the contentSize of the scrollview in your viewDidLoad method.
[myScrollView setContentSize:CGSizeMake(320*3,200)];
Thanks and have a blessed day
So sometimes upon returning to my main menu for my game I am greeted by something quite extraordinary. As you can see from the picture I have replicated cells outside the UIView Table. Now at first I thought it was a graphics corruption that was based on memory issues, Then I discovered you could interact with them, they are valid cells...not ghost images and they respond to code, So I then did a little search and though that my table was stuck in editing mode or something so I call setediting:NO everywhere I could. And it haunts me still.
Does anyone even have the first idea what could be causing this? It does not happen all the time but it only ever seems to happen...IF it does when I am popping back to this screen from another view on top of it. I also can't replicate it consistently so it's hard to fix and know what is causing it.
Please keep in mind I might be doing something or not doing something I have not mentioned so don't forget to ask everything you may think relevant and I will be happy to inform you.
EDIT:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_indexPath = indexPath;
NSLog(#"%i",_indexPath.row);
[_indexPath retain];
[[CurrentGamesInfo sharedCurrentGamesInfo] SetCurrentGameWithIndex:[_indexPath row]];
UIView *tempView = [[[tableView cellForRowAtIndexPath:indexPath] contentView] viewWithTag:200];
if([[[(UIButton*)[tempView viewWithTag:CELL_BUTTONTEXT_ID] titleLabel] text] isEqualToString:#"Waiting"])
{
return;
}
if( ![[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame].isGameReady )
{
[_PopUp OptionsMessage:#"Game Not Ready" withTitle:#"Hold Your Horsies" hideBackButton:YES];
return;
}
NSString *gameID = [[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] GetGameID];
NSLog(#"%i",[[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] GetTurnNumber].intValue);
NSData *pngData = [NSData dataWithContentsOfFile:[AppDelegate applicationDocumentDirectory:gameID]];
UIImage *image = [UIImage imageWithData:pngData];
PhotoImage *photoImg = [[PhotoImage alloc]init];
[photoImg set_imageToSend:image];
[[[CurrentGamesInfo sharedCurrentGamesInfo] _selectedGame] SetImageToSend:photoImg];
[photoImg release];
UIImageView * imgView = (UIImageView*)[[[[tableView cellForRowAtIndexPath:indexPath] contentView]viewWithTag:300] viewWithTag:301];
[[[CurrentGamesInfo sharedCurrentGamesInfo]_selectedGame]setOpponentProfilePic:imgView.image];
[self TempCurrentGameFunction];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
WARNING: HEFTY FUNCTION INCOMING
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
GameInfo *gameThisRow = [[[CurrentGamesInfo sharedCurrentGamesInfo]_currentGames] objectAtIndex:indexPath.row];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSLog(#"row : %i",indexPath.row);
NSLog(#"current game count : %i",[[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames]count]);
NSString *gameType = #"";
UIButton *gameStatusButton = [[UIButton alloc]initWithFrame:CGRectMake(100, -5, 90, 70)];
Boolean isYourTurn = [[gameThisRow GetPlayerRole] intValue] ? YES : NO;
NSString *gameStateString = #"Your Move";
[cell setUserInteractionEnabled:YES];
[cell setTag:ACTIVE_GAME_CELL];
if(!isYourTurn)
{
//_activeGameCount--;
gameStateString = #"Waiting";
[cell setUserInteractionEnabled:NO];
[cell setTag:INACTIVE_GAME_CELL];
}
[gameStatusButton setTitle:gameStateString forState:UIControlStateNormal];
[[gameStatusButton titleLabel] setFont:[UIFont fontWithName:#"Fredoka One" size:10]];
[gameStatusButton setTag:CELL_BUTTONTEXT_ID];
if( indexPath.row < [[[CurrentGamesInfo sharedCurrentGamesInfo] _currentGames]count])
{
switch ([gameThisRow gameType])
{
case 0:
gameType = #"Open Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_blue.png"] forState:UIControlStateNormal];
break;
case 1:
{
gameType = #"Challenge Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_orange.png"] forState:UIControlStateNormal];
}
break;
case 2:
{
gameType = #"Battle Game";
[gameStatusButton setBackgroundImage:[UIImage imageNamed:#"buttonB_pink.png"] forState:UIControlStateNormal];
}
break;
default:
break;
}
}
NSLog(#"%#",[[gameThisRow GetFaceBookData]objectForKey:#"name"]);
NSString *name = [[gameThisRow GetFaceBookData]objectForKey:#"name"];
UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(80, 10, 100, 50)];
[labelView setTag:200];
[labelView addSubview:gameStatusButton];
[gameStatusButton release];
[labelView setBackgroundColor:[UIColor clearColor]];
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 100, 20)];
NSString *text = name;
NSArray *nameArray = [text componentsSeparatedByString:#" "];
NSString *nameWithInitials;
nameWithInitials = [NSString stringWithFormat:#"%#",[nameArray objectAtIndex:0]];
for( int i = 1; i < nameArray.count; ++i )
{
NSString *temp = [nameArray objectAtIndex:i];
nameWithInitials = [nameWithInitials stringByAppendingFormat:#" %C.",[temp characterAtIndex:0]];
}
text = nameWithInitials;
int maxSize = 20;
int minSize = 8;
UIFont *font = [UIFont fontWithName:#"Fredoka One"size:maxSize];
/* Time to calculate the needed font size.
This for loop starts at the largest font size, and decreases by two point sizes (i=i-2)
Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */
for(int i = maxSize; i > minSize; i=i-2)
{
// Set the new font size.
font = [font fontWithSize:i];
// You can log the size you're trying: NSLog(#"Trying size: %u", i);
/* This step is important: We make a constraint box
using only the fixed WIDTH of the UILabel. The height will
be checked later. */
CGSize constraintSize = CGSizeMake([labelName frame].size.width, MAXFLOAT);
// This step checks how tall the label would be with the desired font.
CGSize labelSize = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
/* Here is where you use the height requirement!
Set the value in the if statement to the height of your UILabel
If the label fits into your required height, it will break the loop
and use that font size. */
if(labelSize.height <= [labelName bounds].size.height)
break;
}
// You can see what size the function is using by outputting: NSLog(#"Best size is: %u", i);
// Set the UILabel's font to the newly adjusted font.
[labelName setFont:font];
// Put the text into the UILabel outlet variable.
[labelName setText:text];
[labelName setTextColor:[UIColor grayColor]];
[labelName setBackgroundColor:[UIColor clearColor]];
[labelName setTextAlignment:UITextAlignmentCenter];
[labelView addSubview:labelName];
[labelName release];
UILabel *labelSubtitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 50)];
[labelSubtitle setText:gameType];
[labelSubtitle setFont:[UIFont fontWithName:#"Fredoka One" size:10]];
[labelSubtitle setTextColor:[UIColor grayColor]];
[labelSubtitle setBackgroundColor:[UIColor clearColor]];
[labelSubtitle setTextAlignment:UITextAlignmentCenter];
[labelView addSubview:labelSubtitle];
[labelSubtitle release];
[[cell contentView] addSubview:labelView];
NSString *path = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?width=200&height=200",[[gameThisRow GetFaceBookData]objectForKey:#"id"] ];
UIImageView *pictureImage = [[UIImageView alloc] init];
[pictureImage setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:#"Icon-Small.png"]success:^(UIImage *image)
{
pictureImage.image = [image imageScaledToSize:CGSizeMake(100, 100)];
} failure:^(NSError *error)
{
[pictureImage setImage:[[UIImage imageNamed:#"Icon-Small.png" ]imageScaledToSize:CGSizeMake(50, 50)]];
NSLog(#"%#",[error localizedDescription]);
}];
NSLog(#"%#",[pictureImage image]);
pictureImage.layer.masksToBounds = YES;
[pictureImage setFrame:CGRectMake(pictureImage.frame.origin.x+20, 37 - 25, 50, 50)];
UIImageView *pictureFrameView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"profile_frame.png"]];
CGRect temp = pictureImage.frame;
//hand & hard coded, i feel so ashamed and sullied
temp.origin.x -= 12;
temp.origin.y -= 9;
temp.size.width = 70;
temp.size.height = 73;
[pictureFrameView setFrame:temp];
UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[pictureView addSubview:pictureFrameView];
[pictureView addSubview:pictureImage];
[pictureImage setTag:301];
[pictureFrameView release];
[pictureImage release];
[[cell contentView] addSubview:pictureView];
[pictureView setTag:300];
[pictureView release];
//custom stuff start
UIImage *rowBackground;
//UIImage *selectionBackground;
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"table_bottom.png"];
//selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"table_top.png"];
//selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"table_bottom.png"];
//selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"table_mid.png"];
//selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:rowBackground];
[cell setBackgroundView:imageView];
[imageView release];
//((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
//custom stuff end
__block CGRect newPos = inviteFriendsParentView.frame;
CGRect tempCurrentGameSubMenuFrame = currentGameSubMenu.frame;
tempCurrentGameSubMenuFrame.size.height = [friendsTable rowHeight] * [friendsTable numberOfRowsInSection:0] + 10;
currentGameSubMenu.frame = tempCurrentGameSubMenuFrame;
float bottomofFrameYPos = currentGameSubMenu.frame.size.height;
newPos.origin.y += bottomofFrameYPos;
return cell;
}