Now I create is as follow (my file.h):
UIImageView *pic1, *pic2, *pic3, *pic4, *pic5, *pic6, *pic7, *pic8, *pic9, *pic10;
Then in my (file.m):
UIImageView *pic1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#”picName.png”]];
UIImageView *pic2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#”picName.png”]];
……
UIImageView *pic10 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#”picName.png”]];
I need many instances of UIImageView (number triggered by other factors) of only one in this case picture.
Is there any way to create multiple instances of UIImageView automatically in my file.m, somehow as follow?:
for (int x; (x=10); x++)
{
UIImageView * pic[x] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"myPic.png"]];
}
This example doesn’t work but I’d like to show what I want to program.
Of course you can - that is what the arrays are for:
NSMutableArray *pics = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
[pics addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"myPic.png"]]];
}
In case the name of the picture depends on the index, use NSString's stringWithFormat to produce the name of the picture - for example, you can do it like this:
NSMutableArray *pics = [NSMutableArray array];
for (int i = 0 ; i != 10 ; i++) {
NSString *imgName = [NSString stringWithFormat:#"myPic%d.png"];
[pics addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:imgName]]];
}
If the names of images follow a standard pattern you can just loop over the required amount and build the image name dynamically using the index.
If the names of the images do not follow a standard patten you can chuck them in an array and loop over them
NSArray *imageNames = #[
#"alarm.jpg",
#"bell.jpg",
#"car.jpg"
];
NSMutableArray *imageViews = [[NSMutableArray alloc] init];
for (NSString *imageName in imageNames) {
[imagesViews addObject:({
[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
})];
}
Completely optional - further reading
You could write yourself a simple category that abstracts this looping and collecting the results into a new array. This would allow you to simply write
NSArray *imageNames = #[
#"alarm.jpg",
#"bell.jpg",
#"car.jpg"
];
NSArray *imageViews = [imageNames pas_arrayByMappingWithBlock:^(id obj){
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
}];
The category to do that would look something like this:
#interface NSArray (PASAdditions)
- (NSArray *)pas_arrayByMappingWithBlock:(id (^)(id obj))block
#end
#implementation NSArray (PASAdditions)
- (NSArray *)pas_arrayByMappingWithBlock:(id (^)(id obj))block
{
NSMutableArray *result = [[NSMutableArray alloc] init];
for (id obj in self) {
[result addObject:block(obj)];
}
return [result copy];
}
#end
Related
Is there a better way to iterate the following images?
NSArray *imageNames = #[#"MyImage-0.png", #"MyImage-1.png", #"MyImage-2.png",#"MyImage-3.png",#"MyImage-4.png", #"MyImage-5.png", #"MyImage-6.png", #"MyImage-7.png"];
NSMutableArray *images = [[NSMutableArray alloc] init];
for (int i = 0; i < imageNames.count; i++) {
[images addObject:[UIImage imageNamed:[imageNames objectAtIndex:i]]];
}
mImageView.animationImages = images;
mImageView.animationDuration = 1.5;
[self.view mImageView];
[mImageView startAnimating];
NSInteger imagesCount = 7;
NSMutableArray *images = [[NSMutableArray alloc] init];
for (int i = 0; i <= imagesCount; i++) {
[images addObject:[UIImage imageNamed:[NSString stringWithFormat:#"MyImage-%d", i]]];
}
mImageView.animationImages = images;
mImageView.animationDuration = 1.5;
[self.view mImageView];
[mImageView startAnimating];
You can use enumeration
for(NSString *imageStr in imageNames)
{
[images addObject:[UIImage imageNamed:imageStr]];
}
This takes less time to iterate.
Hope it helps you...!
The better way will be not using for loop. Try this code
+(NSArray*)getSortedArray:(NSMutableArray*)arrayToSort
{
return [arrayToSort sortedArrayUsingSelector:#selector(compare:)];
}
Hope this class method will help you.
You might want to use some handy library, like this one. Look, it even supports GIF!
NSString *urlString = #"http://raphaelschaad.com/static/nyan.gif";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:data];
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
imageView.animatedImage = image;
imageView.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
[self.view addSubview:imageView];
I am creating 5 UIButtons, using a for loop, and would like to put 5 different avatars on the UIButtons. However, only one avatar is filling all 5 buttons.
The code I have constructed looks like the following,
// create a subview for avatar buttons
UIView *avatarView = [[UIView alloc] init];
avatarView.frame = CGRectMake(20, 125, 280, 100); // don't mess with these values.
// avatarView.layer.borderColor = [UIColor redColor].CGColor;
// avatarView.layer.borderWidth = 3.0f;
[self.view addSubview:avatarView];
UIScrollView *avatarScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)];
avatarScroll.contentSize = CGSizeMake(500, 500);
avatarScroll.scrollEnabled = YES;
[avatarView addSubview:avatarScroll];
// fetch Data from Core Data
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Account" inManagedObjectContext:_managedObjectContext];
[fetchRequest setEntity:entity];
// fetch records and handle error
NSError *error;
NSArray *results = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
// sort results array by lastLogin
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"lastLogin" ascending:NO];
NSArray *sortedArray = [NSArray arrayWithObject:sort];
NSArray *sortedArray2 = [results sortedArrayUsingDescriptors:sortedArray];
// how to remove values from NSArray
NSArray *lastLoginArray = [sortedArray2 valueForKey:#"lastLogin"];
// NSLog(#"lastLoginArray = %#",lastLoginArray);
// make an array that only hold 5 values
// NSArray *last5LoginArray;
// for (int i=5; i<[lastLoginArray count]; i++) {
// [last5LoginArray addObject:[lastLoginArray objectAtIndex:i]];
// }
// NSLog(#"last5LoginArray = %#",last5LoginArray);
// NSArray *last5LoginArray = [NSArray arrayWithObjects:lastLoginArray count:4];
// NSArray *last5LoginArray = [NSArray arrayByAddingObjectsFromArray:lastLoginArray count:4];
NSMutableArray *last5LoginArray = [[NSMutableArray alloc] initWithArray:[lastLoginArray subarrayWithRange:NSMakeRange(0, 5)] ];
NSLog(#"last5LoginArray = %#",last5LoginArray);
// NSLog(#"sortedArray2 = %#",sortedArray2);
CGFloat staticX = 0;
CGFloat staticWidth = 80;
CGFloat staticHeight = 80;
CGFloat staticPadding = 5;
// need to put the avatars stored in sortedArray2 in the scrollView
for ( int i = 0; i < 5; i++) {
// do additional loading for avatars
UIButton *avatarButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// the last two values control the size of the button
// avatarButton.frame = CGRectMake(0, 0, 80, 80);
[avatarButton setFrame:CGRectMake((staticX + (i * (staticHeight + staticPadding))),5,staticWidth,staticHeight)];
// make corners round
avatarButton.layer.cornerRadius = 40; // value varies -- // 35 yields a pretty good circle.
avatarButton.clipsToBounds = YES;
// create a stock image
UIImage *btnImage = [UIImage imageNamed:#"HomeBrewPoster1.jpg"];
Account *anAccount;
for ( anAccount in results) {
if([last5LoginArray containsObject:anAccount.lastLogin]) {
NSLog(#"anAccount.lastLogin = %#",anAccount.lastLogin);
UIImage *avatarImg = [UIImage imageWithData:anAccount.avatar ];
// apply avImg to btn
[avatarButton setBackgroundImage:avatarImg forState:UIControlStateNormal];
}
}
if (btnImage == nil) {
NSLog(#"can't find HomeBrewPoster1.jpg");
// apply stock image to button(s)
[avatarButton setBackgroundImage:btnImage forState:UIControlStateNormal];
} else {
}
// this should add 5x buttons
[avatarScroll addSubview:avatarButton];
}
Your innermost for-in loop always sets the last matching avatar to the button, because the current value of i makes absolutely no difference to what the innermost loop does.
You should move the nested loop outside the first loop to prepare the five avatars upfront, and then use i to index into the array of avatars, like this:
NSMutableArray *avatars = [NSMutableArray arrayWithCapacity:5];
for ( anAccount in results) {
if([last5LoginArray containsObject:anAccount.lastLogin]) {
NSLog(#"anAccount.lastLogin = %#",anAccount.lastLogin);
UIImage *avatarImg = [UIImage imageWithData:anAccount.avatar ];
[avatars addObject:avatarImg];
}
}
NSAssert(
avatars.count == last5LoginArray.count
, #"The loop is expected to find as many avatars as there are items in last5LoginArray"
);
for ( int i = 0; i < 5; i++) {
...
// Check that we have enough logins
if (i < last5LoginArray.count) {
[avatarButton setBackgroundImage:avatars[i] forState:UIControlStateNormal];
}
}
Declare button as an array
NSArray *arrImages = [NSArray arrayWithObjects:#"1.jpg",#"2.jpg",#"3.jpg",#"4.jpg",#"5.jpg", nil];
UIButton *button[5];
button[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button[i] addTarget:self action:#selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[button[i] setBackgroundImage:[UIImage imageNamed:[arrImages objectAtIndex:i]] forState:UIControlStateNormal];
[button[i] setTitle:#"Title" forState:UIControlStateNormal];
button[i].frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[avatarScroll addSubview:button[i]];
You can name your images like "HomeBrewPoster0", "HomeBrewPoster1", etc. And add this to choose right image in your loop:
UIImage *btnImage = [UIImage imageNamed:[NSString stringWithFormat:#"HomeBrewPoster%ld.jpg", i]];
I would like to know based on my code, how can i add fade in fade out effect between each images in my NSArray. As i am using these images as background. Changing background without fade in and out looks horrible.
Here is my code.
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *imageNames = #[#"1.jpg", #"2.png", #"3.png", #"4.png",
#"5.png"];
NSMutableArray *images = [[NSMutableArray alloc] init];
for (int i = 0; i < imageNames.count; i++) {
[images addObject:[UIImage imageNamed:[imageNames objectAtIndex:i]]];
}
// Normal Animation
UIImageView *animationImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animationImageView.animationImages = images;
animationImageView.animationDuration = 9;
[self.background addSubview:animationImageView];
[animationImageView startAnimating];}
I am trying to show no. of images in different image view. if i have 3 image then i want show in 3 diff. UIImageView in my View. Here is my code that only shows one image. What have i missed here?
NSArray * _thumbnails = _claimReport.photos.allObjects;
if (_thumbnails.count >0)
{
NSMutableArray *imageViews = [[NSMutableArray alloc] init];
for (int i =1; i<_thumbnails.count; i++)
{
UIImageView *newImageViews = [[UIImageView alloc]initWithFrame:CGRectMake(40, 1700*i+20, 670, 700)];
LAPhoto *photo = [_thumbnails objectAtIndex:i];
[newImageViews setImage:[UIImage imageWithData:photo.photo]];
NSLog(#" newImageViews %# ",newImageViews);
[imageViews addObject:newImageViews];
[self.formView addSubview:newImageViews];
}
NSLog(#"Count %d" , imageViews.count);
}
You can add the images in a scroll view:
self.scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
[self.formView addSubview:self.scrollView];
NSArray * _thumbnails = _claimReport.photos.allObjects;
if (_thumbnails.count >0)
{
NSMutableArray *imageViews = [[NSMutableArray alloc] init];
for (int i =0; i<_thumbnails.count; i++)
{
UIImageView *newImageViews = [[UIImageView alloc]initWithFrame:CGRectMake(40, 800*i+20, 670, 700)];
LAPhoto *photo = [_thumbnails objectAtIndex:i];
[newImageViews setImage:[UIImage imageWithData:photo.photo]];
NSLog(#" newImageViews %# ",newImageViews);
[imageViews addObject:newImageViews];
self.scrollView.contentSize = CGSizeMake(670, 800 *i + 800);
[self.scrollView addSubview:newImageViews];
}
NSLog(#"Count %d" , imageViews.count);
}
I am using this code to generate random image to UIImageView. When I click the button, it apears another image. I would like to ask you how to create four imageviews - click button -> apears four different random images.
ViewController.h
#interface ViewController : UIViewController {
IBOutlet UIImageView *imageView;
// IBOutlet UIImageView *imageView2;
}
-(IBAction) randomImage;
ViewController.m
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg", nil];
int count = [images count]
int index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
// imageView2.image = ....
}
I created four imageViews in storyboard and I was trying something like above // imageView2.image... but it it not the right solution :-)
Thank you for your help
Code to list 4 random image:
NSMutableArray *images = [[NSMutableArray alloc] initWithArray: #[#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg"]];
int countImg = images.count;
for (int i = 0; i < countImg; i++) {
NSInteger index = arc4random() % images.count;
NSLog(#"Image%d name = %#",i , [images objectAtIndex:index]);
[images removeObjectAtIndex:index];
}
Rather than using IBOutlet UIImageView *imageView;, use IBOutletCollection(UIImageView) NSArray *imageViews; and connect all of your image views to this.
Then, in your code:
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg", nil];
NSInteger count = [images count];
for (UIImageView *imageView in self.imageViews) {
NSInteger index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
}
}