scrolling image in UIScrollView in iphone - iphone

i m working one app .in this random number of time image is scroll..and then stop the image..here in my code first random number is generate which is store in n..for eg. random no is generate 12 then 12 times image is scroll after that it stop..
- (void)viewDidLoad
{
int n = 1 + arc4random() % 10 + 10;
NSString *string = [NSString stringWithFormat:#"%i",n];
//lbl.text = string;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
// [kNumImages addObject:[NSNumber numberWithInt:i]];
NSString *imageName = [NSString stringWithFormat:#"%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
lbl.text = string;
[FirstScrollView addSubview:imageView];
[imageView release];
if(n == i){
break;
}
}
i want to stop scrolling when random no is match means n == i how can i do that ?

try this,
- (void)viewDidLoad
{
int n = 1 + arc4random() % 10 + 10;
NSString *string = [NSString stringWithFormat:#"%i",n];
//lbl.text = string;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
if(n == i)
break;
else {
// [kNumImages addObject:[NSNumber numberWithInt:i]];
NSString *imageName = [NSString stringWithFormat:#"%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
lbl.text = string;
[FirstScrollView addSubview:imageView];
[imageView release];
}
}
}

[firstScrollView setContentOffset:CGRectMake(n*firstScrollView.frame.size.width,firstScrollView.frame.size.height)];
All you need is to set content offset of your scrollView.

Related

UIScrollView has White Space above SubViews

I am running across a weird issue, which I can't seem to figure out.
Upon adding multiple SubViews to a ScrollView, the ScrollViews keeps on adding a White Space ontop of the regular image
A bit better with more colors:
This is how it should look like:
The Image is perfectly scrollable.
This is the code I'm using to create the scrollview:
-(void)addImagesToScrollView
{
if (self.product != nil)
{
int imageCount = 0;
if (self.product.labelImage != nil)
{
UIImageView *labelImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
labelImage.image = [UIImage imageWithData:self.product.labelImage];
labelImage.contentMode = UIViewContentModeScaleAspectFit;
labelImage.tag = 100;
[self.scrollView addSubview:labelImage];
imageCount += 1;
}
if (self.product.bottleImage != nil)
{
UIImageView *bottleImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
bottleImage.image = [UIImage imageWithData:self.product.bottleImage];
bottleImage.contentMode = UIViewContentModeScaleAspectFit;
bottleImage.tag = 101;
imageCount += 1;
[self.scrollView addSubview:bottleImage];
}
if (self.product.pourImage != nil)
{
UIImageView *pourImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width * 2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
pourImage.image = [UIImage imageWithData:self.product.pourImage];
pourImage.contentMode = UIViewContentModeScaleAspectFit;
pourImage.tag = 102;
imageCount += 1;
[self.scrollView addSubview:pourImage];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * imageCount, self.scrollView.frame.size.height);
[self.scrollView setContentOffset:CGPointZero animated:NO];
}
}
Edit:
With a BackgroundColor:
use:
bottleImage.layer.color = [UIcolor blueColor].CGColor;
bottleImage.layer.borderWidth = 2.0f;
It will let you see the frame of your UIImageView maybe you are calculating incorrectly the frame
Use below code and you will get desired output. In the following code you app will use album photos and automatically sets size of the scrolling as per the number of images in album. And please modify according to your image repository.
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(#"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(#"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
CGSize imageSize;
imageSize.width= imageView.bounds.size.width;
imageSize.height = imageView.bounds.size.height;
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.frame = imageView.frame;
self.scrollView.contentSize = CGSizeMake(imageSize.width * imgArray.count, imageSize.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.bounces=YES;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[self.scrollView flashScrollIndicators];
[self.view addSubview:self.scrollView];
CGFloat xPos = 0.0;
for (UIImage *image in imgArray) {
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.height);
[self.scrollView addSubview:imageView];
xPos += imageSize.width;
// assuming ARC, otherwise release imageView
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20,320 , 420)];
[self getAllPictures];
}

Create multi page PDF in objective-c

I am trying to create a multipage PDF. I have followed this tutorial.
This is working with a XIB file for static text and then adds a table from code. But the problem I'm having ATM is that when the table is bigger then one page. When the table has more then 9 rows. It should continue on the next page.
This is what I'm doing in code.
+(void)drawPDF:(NSString*)fileName
{
NSMutableDictionary *mutDictValues = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dicValues"] mutableCopy];
NSMutableArray *arrSelectedCities = [[mutDictValues objectForKey:#"cities"]mutableCopy ];
if(arrSelectedCities.count <= 8){
// If there are only 8 rows --> we can fit everyting on one page !
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[self drawLabels];
[self drawLogo];
int xOrigin = 50;
int yOrigin = 350;
int rowHeight = 50;
int columnWidth = 240;
int numberOfRows = 9;
int numberOfColumns = 2;
[self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities];
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}else{
// When we have more then 8 rows we should have 2 pages.
NSLog(#"Create 2 pages");
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
[self drawLabels];
[self drawLogo];
int xOrigin = 50;
int yOrigin = 350;
int rowHeight = 50;
int columnWidth = 240;
int numberOfRows = 9;
int numberOfColumns = 2;
[self drawTableAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin, yOrigin) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows andColumnCount:numberOfColumns withArray:arrSelectedCities];
// Create the PDF context using the default page size of 612 x 792.
UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
int xOrigin2 = 50;
int yOrigin2 = 60;
int numberOfRows2 = ((arrSelectedCities.count+1)-9);
[self drawTableAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns];
[self drawTableDataAt:CGPointMake(xOrigin2, yOrigin2) withRowHeight:rowHeight andColumnWidth:columnWidth andRowCount:numberOfRows2 andColumnCount:numberOfColumns withArray:arrSelectedCities];
}
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();
}
Let me explain what I'm doing here. I have an array that should fill up my tableview. If the array is bigger then 8 then I should use 2 pages. Else everything works with one page.
What this does is, it's creating only the second page....
Can anybody help me?
You should not call UIGraphicsBeginPDFContextToFile() again when creating the second page,
only UIGraphicsBeginPDFPageWithInfo():
UIGraphicsBeginPDFContextToFile(...);
UIGraphicsBeginPDFPageWithInfo(...); // start first page
// ...
UIGraphicsBeginPDFPageWithInfo(...); // start second page
// ...
UIGraphicsEndPDFContext();
NSArray *imageArray = [NSArray arrayWithObjects:[UIImage imageNamed:#"3.png"], [UIImage imageNamed:#"4.png"], [UIImage imageNamed:#"5.png"], [UIImage imageNamed:#"3.png"], nil];
NSMutableData *pdfFile = [[NSMutableData alloc] init];
double pageWidth = 0.0;
double pageHeight = 0.0;
UIImage *image;
for (int i = 0; i < [imageArray count]; i++)
{
image =[UIImage imageWithCGImage:[imageArray[i] CGImage]];
pageWidth = pageWidth + image.size.width ;
pageHeight = pageHeight + image.size.height;
}
image =[UIImage imageWithCGImage:[imageArray[0] CGImage]];
CGRect rect;
rect = CGRectMake(0, 0,image.size.width ,image.size.height);
UIGraphicsBeginPDFContextToData(pdfFile, CGRectZero, nil);
for (int i = 0; i < [imageArray count] ; i++)
{
UIGraphicsBeginPDFPageWithInfo(rect, nil);
UIImage *contextImage = imageArray[i];
[contextImage drawInRect:rect];
}
UIGraphicsEndPDFContext();
// save PDF file
NSString *saveFileName = [NSString stringWithFormat:#"%#%fx%f.pdf", #"test", pageWidth, pageHeight];
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* savePath = [documentDirectory stringByAppendingPathComponent:saveFileName];
if([[NSFileManager defaultManager] fileExistsAtPath:savePath])
{
[[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
}
[pdfFile writeToFile: savePath atomically: YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"PDF File created and saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
You don't need to create context for second page (UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil)), you have to only create this page.
You should also remember about closing opened page using CGPDFContextEndPage().
- (void)viewDidLoad {
[super viewDidLoad];
[self createPDF];
}
- (void)createPDF {
[self setupPDFDocumentNamed:#"myPdf" Width:850 Height:1100];
[self beginPDFPage];
}
- (void)beginPDFPage {
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
// kPadding will make 20 points margin on both sides of pdf
CGRect textRect = [self addText:#"Line Text Testing" withFrame:CGRectMake(PdfPadding, PdfPadding, 400, 200) fontSize:48.0f];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]];
UIImage *anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://www.phantompeer.com/sitefiles/osx.png"]]];
textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]];
textRect = [self addText:#"Line Text Testing" withFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, 400, 200) fontSize:48.0f];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height +PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor blueColor]];
anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://www.w3schools.com/css/img_fjords.jpg"]]];
textRect = [self addImage:anImage atPoint:CGPointMake((pageSize.width/2)-(anImage.size.width/2),textRect.origin.y + textRect.size.height + PdfPadding)];
textRect = [self addLineWithFrame:CGRectMake(PdfPadding, textRect.origin.y + textRect.size.height + PdfPadding, pageSize.width - PdfPadding*2, 4) withColor:[UIColor redColor]];
UIGraphicsEndPDFContext();
[self loadRemotePdf];
}
-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize {
UIFont *font = [UIFont systemFontOfSize:fontSize];
CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:UILineBreakModeWordWrap];
if((frame.origin.y + stringSize.height + PdfPadding) > pageSize.height) {
frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
float textWidth = frame.size.width;
if (textWidth < stringSize.width)
textWidth = stringSize.width;
if (textWidth > pageSize.width)
textWidth = pageSize.width - frame.origin.x;
CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
[text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
return frame;
}
-(CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color {
if((frame.origin.y + frame.size.height+PdfPadding) > pageSize.height) {
frame = CGRectMake(frame.origin.x, PdfPadding, frame.size.width, frame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(currentContext, color.CGColor);
// this is the thickness of the line
CGContextSetLineWidth(currentContext, frame.size.height);
CGPoint startPoint = frame.origin;
CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);
CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathFillStroke);
return frame;
}
-(CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point {
CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height);
if((imageFrame.origin.y + imageFrame.size.height + PdfPadding) > pageSize.height) {
imageFrame = CGRectMake(imageFrame.origin.x, PdfPadding, imageFrame.size.width, imageFrame.size.height);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
}
[image drawInRect:imageFrame];
return imageFrame;
}
- (void) loadRemotePdf
{
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
NSString *newPDFName = [NSString stringWithFormat:#"myPdf.pdf"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
myWebView.autoresizesSubviews = YES;
myWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
NSURL *myUrl = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
[myWebView loadRequest:myRequest];
[self.view addSubview: myWebView];
}
For creating new page in the pdf, use
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

Sharing images using Activityviewcontroller

How can i share images from imagescrollview using ActivityViewController.
Below is the code for displaying images in imagescrollview
UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
imageScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 61;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height);
[imageScrollView addSubview:imageView];
Trying to share images from imagescrollview using activityviewcontroller but in the very first statement getting message in red that expected expression
NSArray *activityItems = #[UIImage imageNamed:]imageView];// **getting message in red expected expression**
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityViewController.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypePrint ];
[self presentViewController:activityViewController animated:YES completion:NULL];
[activityViewController release];
Thanks for help.
Store the images in an array first in the forLoop where you are adding the images to scrollview,then
NSArray *activityItems = [NSArray arrayWithArray:imageArray]; //imageArray is the nsmutablearray in which you shall store the images
You are assigning image to object of Array and Your Syntax is also wrong..
So That's why you are getting getting message in red expected expression this..
Try this code instead of your code
NSMutableArray * activityItems = [[NSMutableArray alloc]init];
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height);
[imageScrollView addSubview:imageView];
[[activityItems addObject:imageView];
}
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityViewController.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypePrint ];
[self presentViewController:activityViewController animated:YES completion:NULL];
[activityViewController release];

iOS programmatically created UIButton action stops working after from 3rd UIView onwards

I created a cool app that programmatically creates over 50+ UIButtons including an action selector.
The action (playing a sound) stops working from the 3rd UIView onwards.
The UIView is inside the UIScrollView and uses paging.
I use iOS 5, but I don't think that is the issue.
Also the sound works fine on the first and second page in the UIScrollView.
Also if I change the amount of buttons (more or less) the sound always works as a charm,
till I reach the 3rd page :/
Here the code:
- (void)setButtons
{
int screenWidth = 320;
int screenHeight = 410;
int rows = krows;
int cols = kcols;
int marginLeft = kmarginLeft;
int height = kheight;
int buttonWidth = kbuttonWidth;
int buttonHeight = kbuttonHeight;
int delta = kdelta; // gap between buttons
int startPosY = kstartPosY;
int startPosX = kstartPosX;
int posY = startPosY;
int posX = startPosX;
int contentWidth = screenWidth;
int intStart = 0;
NSMutableDictionary *dict = [Persistence getDictFromParam:#"Bud"];
NSArray *keys = [dict allKeys];
// sort keys
NSArray *sortedKeys = [keys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
int len = keys.count; //50;
NSLog(#"len: %d", len);
CGSize scrollViewContentSize = CGSizeMake(screenWidth, screenHeight);
[scrollView setContentSize:scrollViewContentSize];
for( int i = intStart; i < len; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton addTarget:self action:#selector(sound1Action:) forControlEvents:UIControlEventTouchUpInside];
NSString *key = [sortedKeys objectAtIndex:i];
if (i > 0) {
posY += delta + height;
int mod = i % rows;
if(mod == 0) {
int mod2 = i % (rows*cols);
if(mod2 == 0) {
posX += marginLeft;
}
posX += (marginLeft + buttonWidth);
// extend pages
if(posX > contentWidth) {
contentWidth += screenWidth;
CGSize scrollViewContentSize = CGSizeMake(contentWidth, screenHeight);
[scrollView setContentSize:scrollViewContentSize];
}
posY = startPosY;
}
}
[aButton setFrame:CGRectMake(posX, posY, buttonWidth, buttonHeight)];
NSString *title = [[NSString alloc] initWithFormat:#"%#", key];
[aButton setBackgroundImage:[UIImage imageNamed:#"button_normal.png"] forState:UIControlStateNormal];
[aButton setBackgroundImage:[UIImage imageNamed:#"button_pushed.png"] forState:UIControlStateHighlighted];
[aButton setBackgroundImage:[UIImage imageNamed:#"button_pushed.png"] forState:UIControlStateSelected];
[aButton setTitle:title forState:UIControlStateNormal];
[aButton setTag:i];
NSLog(#"%#: %d",title, aButton.tag);
[contentView addSubview:aButton];
}
[scrollView setPagingEnabled:YES];
}
- (void)sound1Action:(id)sender {
UIButton *button = (UIButton*)sender;
int i = button.tag;
BackgroundMusic *backgroundMusic = [BackgroundMusic sharedInstance];
NSArray *sortedKeys = [self sortedDict];
NSString *val = [[self getDict] objectForKey:[sortedKeys objectAtIndex:i]];
NSLog(#"%#",val);
NSURL *url = [[NSBundle mainBundle] URLForResource:val withExtension:nil];
NSString *pathUrl = [url path];
backgroundMusic.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathUrl] error:NULL];
[backgroundMusic.player stop];
[backgroundMusic.player play];
[backgroundMusic player].volume = 0.5;
backgroundMusic.player.numberOfLoops = 0; //-1; initite
}

Can I re-coding loop UIImageView to get shorter code?

Can I make this code shorter than this ?
- (void) setupFeature
{ NSArray *numbers = [NSArray arrayWithObjects: #"01", #"02", #"03",#"04",#"05",#"06", nil];
position = CGRectMake(7, position.origin.y+20, 72, 72);
int j=0;
NSString *pic;
UIImageView *a_pic;
NSMutableArray *C_Pic = [[[NSMutableArray alloc] init] autorelease];
for (int i=0; i<[numbers count]; i++)
{
UIImageView *picture = [[UIImageView alloc] init];
[C_Pic addObject:picture];
[picture release];
a_pic = [C_Pic objectAtIndex:i];
pic = [NSString stringWithFormat:#"iconD%#",[numbers objectAtIndex:i]];
a_pic.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:pic ofType:#"png"]];
if(j<4)
{
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
j++;
}
else
{
j=0;
position = CGRectMake(7, position.origin.y+77, 72, 72);
NSLog(#"Pic%i position %#",i, NSStringFromCGRect(self.position));
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
}
}
}
If it can be shorter ?? please , help me how to do that ?
Yes it can be shorter see this
- (void) setupFeature
{
NSArray *numbers = [NSArray arrayWithObjects: #"01", #"02", #"03",#"04",#"05",#"06", nil];
position = CGRectMake(7, position.origin.y+20, 72, 72);
int j=0;
NSString *pic;
UIImageView *a_pic;
NSMutableArray *C_Pic = [[[NSMutableArray alloc] init] autorelease];
for (int i=0; i<[numbers count]; i++)
{
UIImageView *picture = [[UIImageView alloc] init];
[C_Pic addObject:picture];
[picture release];
a_pic = [C_Pic objectAtIndex:i];
pic = [NSString stringWithFormat:#"iconD%#",[numbers objectAtIndex:i]];
a_pic.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:pic ofType:#"png"]];
if(j<4)
{
j++;
}
else
{
j=0;
position = CGRectMake(7, position.origin.y+77, 72, 72);
NSLog(#"Pic%i position %#",i, NSStringFromCGRect(self.position));
}
//No need to repeat this code
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
}
}