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

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

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.

UIImageView tap gesture not working on image tap

I have assigned a image in table footer, the tap is recognized just on few pixels outside the image's top left, BUT not on the image taping. Can you pls correct me where I'm doing the mistake. I wanted the call a method when the image is tapped.
Here is the code.
-(UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
if(section==1)
{
UIView *headerView = [[UIView alloc] init];
timgview = [[UIImageView alloc] initWithFrame:CGRectMake(285, 5, 20, 20)];
timgview.image = [UIImage imageNamed:#"icon.png"];
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(openURL:)];
tapped.numberOfTapsRequired = 1;
tapped.numberOfTouchesRequired = 1;
[timgview addGestureRecognizer:tapped];
timgview.userInteractionEnabled = YES;
[headerView addSubview:timgview];
return headerView;
}
}
-(void)openURL:(id) sender
{
NSLog(#"Opening URL");
}

how can I make a scrollView autoscroll?

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.

Posting images from camera roll to facebook in xcode 4.5

I've got some functionality set up. But I'm lost on where to go from here. I can probably figure out what to do with facebook once I know how to actually use the images. I tried saving the image into NSDictionary and then redirecting to a different View Controller, but it won't let me redirect from within the imagePickerController method. So anybody have any idea how to use the image selected from camera roll?
My next idea was to save it in the NSDictionary and then just have a statement checking to see if the NSdictionary value changed but that's not an efficient way of doing it at all.
EDITED below to include the answer provided, but nothing happens, no image displays or anything. What am I missing?
- (void) useCameraRoll
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
newMedia = NO;
}
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
NSLog(#"image:%#",image);
displayPhoto.image = image;
[displayPhoto setFrame:CGRectMake(0, 0, 320, 480)];
[[self view] addSubview:displayPhoto];
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
Assuming you have called this from a view controller with a button that you have created, why not just add a UIImageView onto your view controller? Call it myPhotoImageView or something like that and then in the didFinishPickingMediaWithInfo method, just add the following line of code after
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
as
myPhotoImageView.image = image;
To size the image view so that the aspect looks nice do this.
CGSize size = image.size;
CGRect photoFrame;
if (size.width > size.height)
{
// Landscape
CGFloat scaleFactor = 320 / size.width;
photoFrame = CGRectMake(0, 0, 320, size.height*scaleFactor);
}
else
{
// Portrait
CGFloat scaleFactor = 320 / size.height;
photoFrame = CGRectMake(0, 0, size.width*scaleFactor, 320);
}
myPhotoImageView.frame = photoFrame;

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