how can I make a scrollView autoscroll? - xcode

I have this scrollView:
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.scrollView.contentSize = CGSizeMake(320,3000);
_scrollView.frame = CGRectMake(0, 45, 320, 420);
and I want to make it autoscroll very slowly downward to the end so that the user can see the content (as in movie credits), eventually with a button to stop/play, but to follow the user gestures when touching the interface.
How can I do this?
Thanks,

You can use:
[_scrollView setContentOffset:CGPointMake(x,y) animated:YES];
and use the x and y as the touch points on the screen you can capture.
You can also do an animation with CoreAnimation:
[UIScrollView beginAnimations:#"scrollAnimation" context:nil];
[UIScrollView setAnimationDuration:1.0f];
[scroll setContentOffset:CGPointMake(x, y)];
[UIScrollView commitAnimations];

this adapted code did the trick (source http://sugartin.info/2012/01/21/image-sliding-page-by-page-uiscrollview-auto-scrolling-like-image-slider/)
PS : each image is 280 by 200
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollView *scr=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scr.tag = 1;
scr.autoresizingMask=UIViewAutoresizingNone;
[self.view addSubview:scr];
[self setupScrollView:scr];
UIPageControl *pgCtr = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 264, 480, 36)];
[pgCtr setTag:12];
pgCtr.numberOfPages=10;
pgCtr.autoresizingMask=UIViewAutoresizingNone;
[self.view addSubview:pgCtr];
}
- (void)setupScrollView:(UIScrollView*)scrMain {
// we have 10 images here.
// we will add all images into a scrollView & set the appropriate size.
for (int i=1; i<=10; i++) {
// create image
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"sti%02i.jpg",i]];
// create imageView
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(20, ((i-1)*scrMain.frame.size.height+100), 280, 200)];
// set scale to fill
imgV.contentMode=UIViewContentModeScaleToFill;
// set image
[imgV setImage:image];
// apply tag to access in future
imgV.tag=i+1;
// add to scrollView
[scrMain addSubview:imgV];
}
// set the content size to 10 image width
[scrMain setContentSize:CGSizeMake(scrMain.frame.size.width, scrMain.frame.size.height*10)];
// enable timer after each 2 seconds for scrolling.
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(scrollingTimer) userInfo:nil repeats:YES];
}
- (void)scrollingTimer {
// access the scroll view with the tag
UIScrollView *scrMain = (UIScrollView*) [self.view viewWithTag:1];
// same way, access pagecontroll access
UIPageControl *pgCtr = (UIPageControl*) [self.view viewWithTag:12];
// get the current offset ( which page is being displayed )
CGFloat contentOffset = scrMain.contentOffset.y;
// calculate next page to display
int nextPage = (int)(contentOffset/scrMain.frame.size.height) + 1 ;
// if page is not 10, display it
if( nextPage!=10 ) {
[scrMain scrollRectToVisible:CGRectMake(0, nextPage*scrMain.frame.size.height, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
pgCtr.currentPage=nextPage;
// else start sliding form 1 :)
} else {
[scrMain scrollRectToVisible:CGRectMake(0, 0, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
pgCtr.currentPage=0;
}
}

You can set x if you want to scroll horizontally, otherwise set y to scroll vertical.
[_scrollView setContentOffset:CGPointMake(x, y) animated:YES];
and modify the co-ordinates accordingly.

Related

UIImageView filling entire UICollectionView cell

I have a UICollectionView displaying a horizontal layout of images. Under each image, I'm displaying a label. In the storyboard, I've extended the height of the cell so that the label will be displayed underneath the cell. I've also set the height of the UIImageView in storyboard to be 20pts less than the cell. However, no matter what I do, the images take up the entire cell and the label is displayed on top of the image. Should I be setting the size of the imageview elsewhere? I found this thread which I thought would help since it's basically, identical, but the solution did not help me.
Here is my code...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell"; // string value identifier for cell reuse
ImageViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.layer.borderWidth = 1.0;
cell.layer.borderColor = [UIColor grayColor].CGColor;
NSString *myPatternString = [self.imageNames objectAtIndex:indexPath.row];
cell.imageView.image = [self.imagesArray objectAtIndex:indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.clipsToBounds = YES;
CGSize labelSize = CGSizeMake(CellWidth, 20);
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(cell.bounds.size.width/2, cell.bounds.size.height-labelSize.height, cell.bounds.size.width, labelSize.height)];
testLabel.text = myPatternString;
[cell.contentView addSubview:testLabel];
return cell;
}
Don't know if this will work for you, but I do this will a subclass of UIView which contains two subviews -- a UIImageView for the image and a UILabel for the label. Here is the essence of that subclass below (don't be bothered by the rounding of bottoms; in some areas I need the bottoms to be rounded, in others I don't). I just add this subview to the contentView of the cell. Don't know if it helps you but here it is. BTW, imageView is a class variable here but you might define it as a property.
- (id)initWithFrame:(CGRect)frame withImage:(UIImage *)img withLabel:(NSString *)lbl roundBottoms:(BOOL)roundBottoms;
{
self = [super initWithFrame:frame];
if (self)
{
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height-25.0f)];
if (roundBottoms)
{
imageView.layer.cornerRadius = 12;
imageView.layer.masksToBounds = YES;
}
else
{
CAShapeLayer * maskLayer = [CAShapeLayer layer];
maskLayer.path = [UIBezierPath bezierPathWithRoundedRect: imageView.bounds byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){12.0, 12.}].CGPath;
imageView.layer.mask = maskLayer;
}
[imageView setImage:img];
imageView.contentMode = UIViewContentModeScaleAspectFill; // default
[self addSubview:imageView];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 25.0f, frame.size.width, 25.0f)];
label.text = lbl;
labelText = lbl;
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor blackColor];
label.adjustsFontSizeToFitWidth = YES;
label.minimumScaleFactor = 0.50f;
label.backgroundColor = [UIColor clearColor];
self.tag = imageItem; // 101
[self addSubview:label];
}
return self;
}
I have another version of it I use where I calculate the height of the label based on the overall frame height that is passed in. In this one, the cell sizes are static so the label heights can be as well.

how to show images as a gridview like format in uiscrollview in ios?

its just a week that am into ios devlopement and am facing some problem that i cant show the images in scrolview with gridview format...i dont know how to set the frame size to show images in proper gridview format..
here is my code
that add 5 images in scrollview
for(int i=1;i<6;i++)
{
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(x+0, 0, 320, 460)];
[image setImage:[UIImage imageNamed:[NSString stringWithFormat:#"e1%d.png",i]]];
[scr addSubview:image];
x+=320;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.delegate = self;
image.userInteractionEnabled = YES;
[image addGestureRecognizer:tapGesture];
}
scr.pagingEnabled=YES;
scr.contentSize = CGSizeMake(320*5, 300);
[self.view addSubview:scr];
but all 5 images shows in one horizontal line but i want to show in every line 2 images.
here is the solution, i've implemented it in my app. Here is my code sv_port is my scrollView. Download SDWebImageDownloader class files and import it in your project. Add
relevant framework in your project. like imageIO.framework, QuartzCore
if your images are not fetching from url, then u dont need to use asyncImage view., so dont need to download SDWebImageDownloader.
Now, in your .m add
#import "UIImageView+WebCache.h"
#import "SDImageCache.h"
#import "SDWebImageCompat.h"
//function for adding image in your scrollview
-(void)populateImages
{
int x=6,y=6;
for(UIView * view in sv_port.subviews)
{
if([view isKindOfClass:[UIImageView class]])
{
[view removeFromSuperview]; view = nil;
}
if([view isKindOfClass:[UIButton class]])
{
[view removeFromSuperview]; view = nil;
}
}
for(int p=0;p<[Manufacturer count];p++)
{
UIButton *btnImageButton = [UIButton buttonWithType:UIButtonTypeCustom];
btnImageButton.frame = CGRectMake(x,y,70,70);
[btnImageButton setTag:p];
[btnImageButton addTarget:self action:#selector(nextview:) forControlEvents:UIControlEventTouchUpInside];
UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinny.frame=CGRectMake(btnImageButton.frame.origin.x+25,btnImageButton.frame.origin.y+25, 20, 20);
spinny.backgroundColor=[UIColor clearColor];
[spinny startAnimating];
[sv_port setScrollEnabled:YES];
[sv_port addSubview:spinny];
UIImageView *asyncImageView = [[[UIImageView alloc] initWithFrame:btnImageButton.frame] autorelease];
asyncImageView.backgroundColor=[UIColor clearColor];
CALayer *layer;
layer = asyncImageView.layer;
layer.borderWidth = 0.5;
layer.cornerRadius = 5;
layer.masksToBounds = YES;
[asyncImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", yourUrl] ] placeholderImage:[UIImage imageNamed:nil] options:0 andResize:CGSizeMake(btnImageButton.frame.size.width,btnImageButton.frame.size.height) withContentMode:UIViewContentModeScaleAspectFit];
asyncImageView.contentMode = UIViewContentModeScaleAspectFit;
[sv_port addSubview:btnImageButton];
[sv_port addSubview:asyncImageView];
int imgCntPort=0;
imgCntPort=(sv_port.frame.size.width/(asyncImageView.frame.size.width));
//NSLog(#"imgport %d",imgCntPort);
if((p+1)%imgCntPort==0)
{
x=5;
y=y+80;
}
else
{
x=x+80;
}
}
sv_port.contentSize = CGSizeMake(0, y);
glob_x =0; glob_y =y;
}
By this code you will get 4 images in a row., By the change co-Ordiante of x and y you can maintain number of images per row to display.
Hope this helps. Thanks

Image size resets to original after performing pich using UIPichGestureRecognizer in iphone

I have one view controller in which I have added UIScrollView & UIImageView programatically. I have added UIPichGestureRecognizer to the UIImageView. My UIImageView is added to UIScrollView as a subview.
My problem is when I try to pinch the image , it zoom in. But when I release the touches from screen it again come to its default size. I can not find the error in code. Please help me.
Below is my code
- (void)createUserInterface {
scrollViewForImage = [[UIScrollView alloc]initWithFrame:CGRectMake(20.0f, 60.0f, 280.0f, 200.0f)];
scrollViewForImage.userInteractionEnabled = YES;
scrollViewForImage.multipleTouchEnabled = YES;
scrollViewForImage.backgroundColor = [UIColor redColor];
scrollViewForImage.autoresizesSubviews = YES;
scrollViewForImage.maximumZoomScale = 1;
scrollViewForImage.minimumZoomScale = .50;
scrollViewForImage.clipsToBounds = YES;
scrollViewForImage.delegate = self;
scrollViewForImage.bouncesZoom = YES;
scrollViewForImage.contentMode = UIViewContentModeScaleToFill;
[self.contentView addSubview:scrollViewForImage];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 280.0f, 200.0f)];
[imageView setBackgroundColor:[UIColor clearColor]];
imageView.userInteractionEnabled = YES;
imageView.multipleTouchEnabled = YES;
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(pinch:)];
[pinchRecognizer setDelegate:self];
[imageView addGestureRecognizer:pinchRecognizer];
//[self.contentView addSubview:imageView];
[self.scrollViewForImage addSubview:imageView];
scrollViewForImage.contentSize = CGSizeMake(imageView.frame.size.width , imageView.frame.size.height);
}
-(UIView *) viewForZoomingInScrollView:(UIScrollView *)inScroll {
return imageView;
}
-(void)pinch:(id)sender {
[self.view bringSubviewToFront:[(UIPinchGestureRecognizer*)sender view]];
if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
lastScale = 1.0;
return;
}
CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
[[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)sender scale];
}
From what I can see the problem lies here:
scrollViewForImage.maximumZoomScale = 1;
You are setting the maximum zoom scale of the image to 1 x its full size. This means once you finish pinching the image, it will scale back to 1 x its size.
If you want to be able to zoom the image to a larger size, try settings this value to be higher than 1. e.g.
scrollViewForImage.maximumZoomScale = 3;

Custom scroll view - image outside the frame

I would like to make an infinite scrolling view for iPad. The scrolling works, only when I add pictures to my customized scrollview class, it appears out of the view's frame too (so I have view, which has a UIScrollView on it. This scroll view is connected with my CustomScroll.h :UIScrollView and CustomScroll.m files). Why do the images appear outside the view's frame (the view's frame is set in nib file to 320x420)?
CustomScroll.h:UIScrollView
A part from CustomScroll.m file:
- (id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super initWithCoder:aDecoder])){
self.contentSize = CGSizeMake(2000, 416);
[self setShowsVerticalScrollIndicator:NO];
for (int i=1; i<=4; i++){
[self addImageAtPosition:i];
}
//todo: to replace with the method: addFirstElementToTheEnd
UIImageView *image1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image1.jpg"]];
[image1 setFrame:CGRectMake(5*320, 0, 320, 416)];
[self addSubview:image1];
[image1 release];
//todo: to replace with the method: addLastElementToTheBeginning
UIImageView *image2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image4.jpg"]];
[image2 setFrame:CGRectMake(0*320, 0, 320, 416)];
[self addSubview:image2];
[image2 release];
}
return self;
}
- (void)addImageAtPosition:(NSInteger)position{
UIImageView *tempImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"image%d.jpg", position]]];
[tempImage setFrame:CGRectMake((position * 320), 0, 320, 416)];
[self addSubview:tempImage];
[tempImage release];
}
- (void)recenterIfNecessary{
CGFloat currentOffsetX = [self contentOffset].x;
if (currentOffsetX > 1600.00){
self.contentOffset = CGPointMake(320, [self contentOffset].y );
}
if (currentOffsetX < 320.00){
self.contentOffset = CGPointMake(5*320, [self contentOffset].y);
}
}
- (void) layoutSubviews{
[super layoutSubviews];
[self recenterIfNecessary];
}
TY.

Xcode: Scrollview with images in scrollview

I'm trying to make a view looking almost like the info-view in appStore, with text on the first half of the view and images on the second half. I've tried to use a scrollview in another scrollview. The first view (containing a textview on the top half and a scrollview on the bottom half) scrolls nice, but the scrollview at the bottom (containing several imageviews) doesn't scroll.
Any ideas how to make the second scrollview to scroll?
scrollView is the view containing a textview and a scrollview.
imageScrollView is the view with the imageviews.
[scrollView setContentSize:CGSizeMake(320, 585)];
[imageScrollView setContentSize:CGSizeMake(1520, 400)];
I recently figured it out myself, but forgot to post the answer. The problem was that I set the sizes of the scrollviews in .xib to the same sizes as in the code. When I changed it to 320,416 and 320,400 I was able to scroll them with the setContentSize. In the imageScrollView I then added images along the x-axis (first image at 0, second at image width + a small space and so on). Hope this could help someone.
HERE IS CODE OF scroll-view display images from Documents Directory ByType .png Images who seved by user from Iphone Photo Gallery
- (void)viewDidLoad {
int scrollviewwidh = 120;
self.view.backgroundColor = [UIColor darkTextColor];
hiImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 240)];
hiImage.backgroundColor = [UIColor blackColor];
hiImage.userInteractionEnabled = YES;
[hiImage.layer setBorderColor:[UIColor blackColor].CGColor];
[hiImage.layer setBorderWidth:2.01f];
[self.view addSubview:hiImage];
[hiImage release];
scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 260, 320, 110)];
[self.view addSubview:scroll];
scroll.showsHorizontalScrollIndicator = NO;
scroll.pagingEnabled=YES;
scroll.delegate=self;
scroll.contentSize=CGSizeMake(scrollviewwidh,80);
scroll.showsVerticalScrollIndicator =YES;
scroll.backgroundColor = [UIColor darkTextColor];
}
-(void) viewWillAppear:(BOOL)animated{
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths objectAtIndex:0];
NSLog(#"the ----------- %#",documentsDir);
for (UIButton * img in self.scroll.subviews) {
[img removeFromSuperview];
img = nil;
}
int xoffcet = 0;
int col = 0;
int scrollviewwidh = 120;
for (NSString* fileName in [self.fileManager contentsOfDirectoryAtPath: self.documentsDir error:nil]){
if ( [fileName rangeOfString:#".png"].location != NSNotFound ) {
NSLog(#"add %#", fileName);
UIImage* img = [UIImage imageWithContentsOfFile:
[self.documentsDir stringByAppendingPathComponent:fileName]
];
imgView = [[UIButton alloc] init];
[imgView setImage:img forState:UIControlStateNormal];
[imgView addTarget:self action:#selector(imageViewClicked:) forControlEvents:UIControlEventTouchUpInside];
[imgView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[imgView.layer setBorderWidth:1.0f];
imgView.bounds = CGRectMake(10,10, 50, 50);
imgView.frame = CGRectMake(5+xoffcet, 0, 160, 110);
scroll.contentSize =CGSizeMake(scrollviewwidh+xoffcet,110);
[scroll addSubview:imgView];
[imgView release];
xoffcet +=170;
}
if (col++>1) {
//row++;
col = 0;
}
}
self.title = #"saved Photo";
// [scroll release];
[super viewDidLoad];
// scroll.pagingEnabled = YES;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:
UIBarButtonSystemItemCancel
target:self
action:#selector(photogallary:)];
}
-(IBAction)imageViewClicked:(UIButton *)sender{
for (NSString* fileName in [self.fileManager contentsOfDirectoryAtPath: self.documentsDir error:nil]){
if ( [fileName rangeOfString:#".png"].location != NSNotFound ) {
NSLog(#"add %#", fileName);
UIImage* img = [UIImage imageWithContentsOfFile:
[self.documentsDir stringByAppendingPathComponent:fileName]];
hiImage.image = img;
}
}
}
All The Very Best i Hope its useful Thank You If Thats code Help please give Your Feedback

Resources