NSMutableArray of UIImages - view stays stuck with last image - objective-c

I'm sure that I'm missing something terribly easy here...
I loop through the images just fine the first time, the indices reset and increment properly, but the UIView doesn't refresh and keeps the last image in the array showing. transitionFromView: automatically swaps the subviews, right? Do I need to implement the completion: option?
What am I missing? Here's the pertinent code:
- (id)initWithFrame:(CGRect)frame
{
NSInteger maxSlides = 12;
self = [super initWithFrame: frame];
if (self) {
//set up an array of images to be used for a flipbook
slides = [[NSMutableArray alloc] initWithCapacity: maxSlides];
for(NSInteger i=0; i<maxSlides; ++i) {
imageView = [[UIImageView alloc] initWithImage:
[UIImage imageNamed:[NSString stringWithFormat: #"muybridge%d.png", i]]];
[slides addObject: imageView];
}
index = 0; //default to first photo.
[self addSubview: [slides objectAtIndex: index]];
}
return self;
}
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event
{
//output indices for debugging. (yes, they increment properly)
NSLog(#"index = %d", index);
NSLog(#"currentIndex = %d", currentIndex);
NSLog(#"nextIndex = %d", nextIndex);
if (nextIndex <= 10) {
currentIndex = nextIndex;
} else {
currentIndex = 0;
}
nextIndex = currentIndex + 1;
//flipbook - tapping the image transitions to the next image in the array
[UIView transitionFromView: [slides objectAtIndex: currentIndex]
toView: [slides objectAtIndex: nextIndex]
duration: 0
options: UIViewAnimationOptionTransitionCurlUp
completion: NULL
];
}

What you're missing is this, from the docs on transitionFromView: toView:... :
fromView
The starting view for the transition. By default, this view is removed from its superview as part of the transition.
So it works, the first time through, but only one subview, the last one, remains after you've looked at them all. Look at the UIViewAnimationOptionShowHideTransitionViews option.

According to the Apple reference for UIView: transitionFromView: toView:... :
This method modifies the views in their view hierarchy only. It does not modify your application’s view controllers in any way. For example, if you use this method to change the root view displayed by a view controller, it is your responsibility to update the view controller appropriately to handle the change.
Maybe try calling the [yourView setNeedsDisplay] method right after.

Related

UITabBarController Subviews Don't Appear Weirdness

I have a curious issue with an iOS 9/ObjC app I am writing using a 4 tab format. The "main" ViewController has several subviews with controls and an image. When the user taps the image a PickerView pops up and it is dismissed with another tap on the image. The other tabbed ViewControllers lead to simple views. It was all put together with IB, except for a single subview on the "main" view where I do some Quartz animation drawing superimposed on the image view there.
If I stay on and interact with just the "main" view, all works exactly as desired. The PickerView appears and disappears as designed. Tabbing to another ViewController, then back to the "main" View leads to the problem: A tap on the image view fails to pop up the Picker. The tap is recognized in the Quartz layer, fires a Notification event which is picked up in the picked up in the main view controller which in turn adds the picker subview, brings it to the front and enables interaction just as when it works properly, but the picker never appears, even though the Debugger shows it successfully added to the subview array.
Even stranger, if I tab off the main to any other tab view, then back to main, the picker now appears again as it should. This sequence is completely repeatable - tab once off the main, and the picker doesn't visualize, tab again and then back to main and the picker works.
Any thoughts on where to start looking? Thanks
Here's some code (but I'm not sure where the problem is)
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.picker = [[UIPickerView alloc] init];
self.picker.datasource = self;
self.picker.delegate = self;
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 3 / 4;
// Calculate the starting x coordinate.
float xPoint = screenWidth / 2 - pickerWidth / 2;
[self.Picker setFrame: CGRectMake(xPoint, 50.0f, pickerWidth, 250.0f)];
[self.Picker setClipsToBounds:NO];
[self.Picker setBackgroundColor:[UIColor whiteColor]];
self.Picker.showsSelectionIndicator = YES;
self.Picker.userInteractionEnabled = YES;
.
.
.
UIImage *base = [UIImage imageNamed:#"Base"];
self.baseAView = [[UIImageView alloc] initWithFrame:imFrame];
[self.baseView setImage:base];
[self.view addSubview:_baseView];
self.GView = [[GView alloc] initWithFrame:imFrame];
self.GView.backgroundColor = [UIColor clearColor];
[self.view addSubview:_GView];
}
-(void) viewDidAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doSin) name:#"touchP" object:nil];
}
- (void) doSin {
// user hits GView, draw Picker if not in View Hierarchy, if in Hierarch, grab value and resign
NSArray *subViews = [self.view subviews];
__block NSInteger foundIndex = NSNotFound;
[subViews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UIPickerView class]]) {
foundIndex = idx;
// stop the enumeration
*stop = YES;
}
}];
if (foundIndex != NSNotFound) {
// Found the UIPickerView in subviews, so grab value & remove from screen
[self.view.subviews[foundIndex] removeFromSuperview];
} else {
// not in hierarchy, so put it up on screen
[self.view addSubview:self.Picker];
[self.view bringSubviewToFront:self.Picker];
self.view.userInteractionEnabled = YES;
}
}

UIScrollView with UIViews not shown

I'm trying to use a UIScrollView with UIViews (to manage them as xib files), for now I have an array where I store the views.
testingView is a UIViewcontroller with his own xib file and testingView2 is also an UIViewcontroller with his own different xib file
- (void) viewDidLoad {
[super viewDidLoad];
_testingView = [[TestingViewController alloc] init];
_testingView2 = [[TestingViewController2 alloc] init];
self.array = [[NSArray alloc] initWithObjects: _testingView.view, _testingView2.view, nil];
for (int i = 0; i < [array count]; i++) {
CGRect frame;
frame.origin.x = self.scrollingView.frame.size.width*i;
frame.origin.y = 0;
frame.size = self.scrollingView.frame.size;
[self.scrollingView addSubView: [self.array objectAtIndex:i]];
}
self.scrollingView.contentSize = CGSizeMake (_scrollingView.frame.size.width*[array count], _scrollingView.frame.size.height);
}
the problem is that he is taking only the first view (even if I switch them) and the second view is not shown, the same with UIImages instead of views is working, can someone explain me why? seems like he is not seeing the second view in the array order...
Why are you calculating the variable "frame" inside the for loop when you are not using it?
In my view you should make the following change to your code.
for (int i = 0; i < [array count]; i++) {
CGRect frame;
frame.origin.x = self.scrollingView.frame.size.width*i;
frame.origin.y = 0;
frame.size = self.scrollingView.frame.size;
**UIView *v=[self.array objectAtIndex:i];**
**v.frame=frame;**
**[self.scrollingView addSubView:v];**
}
Hope it works.
In the for loop, you calculate frame for newly added subview, but you don't set that frame to that subview.
In your loop, add your subview like this for example:
UIView *subview = (UIView *)[array objectAtIndex:i];
subview.frame = frame;
[self.scrollingView addSubView:subview];
You need to set the frame for each of the subviews in the scrolling view. For example, you can set the frame of _testingView2.view to be the offset of x from the _testingView1.view frame width.
_testingView2.view.frame = CGRectOffset(_testingView2.frame, CGRectGetWidth(_testingView1.frame), 0)
There are many ways to calculate the frame. Try to use the methods CGRectWidth, CGRectGetMaxX, etc.

UIScrollView with UIImageview and gestures using transitionFromView acting strange

I made a view which holds a UIScrollview:
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 65, 300, 188)];
//BackViews will hold the Back Image
BackViews = [[NSMutableArray alloc] init];
for (int i=0; i<BigPictures.count; i++) {
[BackViews addObject:[NSNull null]];
}
FrontViews = [[NSMutableArray alloc] initWithCapacity:BigPictures.count];
[self.pageControl setNumberOfPages:BigPictures.count];
Then I add several UIImageviews containing images:
//BigPictures holds objects of type UIImage
for (int i = 0; i < BigPictures.count; i++) {
UIImageView *ImageView = [[UIImageView alloc] initWithImage:[BigPictures objectAtIndex:i]];
ImageView.frame = [self.scrollView bounds];
[ImageView setFrame:CGRectMake(self.scrollView.frame.size.width * i, ImageView.frame.origin.y, ImageView.frame.size.width, ImageView.frame.size.height)];
//this saves the FrontView for later (flip)
[FrontViews insertObject:ImageView atIndex:i];
[self.scrollView addSubview:test];
}
// Detect Single Taps on ScrollView
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flip)];
[self.scrollView addGestureRecognizer:tap];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
Ok so far so good. Now the method which does the flipImage part:
- (void)flip {
int currentPage = self.pageControl.currentPage;
UIView *Back = nil;
if ([BackViews objectAtIndex:currentPage] == [NSNull null]) {
//CreateBackView is just creating an UIView with text in it.
Back = [self CreateBackView];
[BackViews replaceObjectAtIndex:currentPage withObject:Back];
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[BackViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];
} else {
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[FrontViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromRight completion:NULL];
[BackViews replaceObjectAtIndex:currentPage withObject:[NSNull null]];
}
[self.view addSubview:Back];
[self rebuildScrollView];
}
This is what rebuildScrollView does:
- (void)rebuildScrollView
{
for (UIView *subview in self.scrollView.subviews) {
[subview removeFromSuperview];
}
for (int i = 0; i < BigPictures.count; i++) {
if ([BackViews objectAtIndex:i] == [NSNull null]) {
[self.scrollView addSubview:[FrontViews objectAtIndex:i]];
} else {
[self.scrollView addSubview:[BackViews objectAtIndex:i]];
}
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
}
So the behavior is the following:
If I click on the first image (1 of 3 in scrollview) the effect is the way I want it, meaning the frontimage turns around and shows the empty (white) back with some text in the middle
If I click on the second image, the image turns but the back is completely empty showing the grey background of the window. If I scroll to the other images, the still show the front image (as expected)
Now I click on the third image and its the same as 1) great.
Current layout is now [BackView, Nothing, Backview)
Lets run that again. But now I click on the last image and its the same as 2) :(
Any ideas whats going wrong here?
EDIT: Some new findings. I doubled the amount of pictures and this is how Front and Backviews are placed (after flipping each one). P = Picture & B = Backview.
P_1(B_1) - actually the only correct one
P_2(empty - should be B_2)
P_3(B_2 - should be B_3)
P_4(empty - should be B_4)
P_5(B_3 - should be B_5)
P_6(empty - should be B_6)
Did a complete rebuild and now it works. Really strange because I used the exact same code.

Gesture recognizers on subviews don't seem to work

I have code as the following:
- (void)setPosts:(NSArray *)posts
{
_posts = posts;
int totalHeight = 0;
for (TumblrPost *post in posts) {
totalHeight += post.thumbH;
}
dispatch_queue_t mainQ = dispatch_get_main_queue();
dispatch_async(mainQ, ^{
int cumulativeY = 0;
int postCount = 0;
for (TumblrPost *post in posts) {
NSArray* array = [[NSBundle mainBundle] loadNibNamed:#"ThumbnailView" owner:nil options:nil];
ThumbnailView* thumbnail = [array objectAtIndex:0];
thumbnail.frame = CGRectMake(0,cumulativeY,0,0);
thumbnail.userInteractionEnabled = YES;
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showMainImage:)];
[thumbnail addGestureRecognizer:gesture];
[self.multiThumbnailView addSubview:thumbnail];
[thumbnail loadUrl:post.url];
cumulativeY+=100;//post.thumbH;
if(postCount >=2)
break;
postCount++;
}
NSLog(#"Set posts method");
});
}
- (void)showMainImage:(UITapGestureRecognizer *)gesture
{
if(gesture.state == UIGestureRecognizerStateChanged || gesture.state == UIGestureRecognizerStateEnded)
{
int thumbIndex = [self.multiThumbnailView.subviews indexOfObject:gesture.view];
self.selectedPost = (TumblrPost*)[self.posts objectAtIndex:thumbIndex];
[self performSegueWithIdentifier:#"ShowMainPost" sender:self];
}
}
multiThumbnailView is a UIView which I have in my storyboard and ThumbnailView is an xib/class combination which is a 100x100 square with a label in it that says 'test'.
When I run my code I get three boxes in a vertical line but the gesture recogniser doesn't fire when I click on my sub views. Everything has userInteractionEnabled ticked. I tried making a test gesturerecognizer on the main multiThumbnailView and that worked.
Please help!
My guess is that ThumbnailView is a subclass of UIImageView - which by default sets its userInteractionEnabled to NO.
Make sure that you set userInteractionEnabled = YES on every ThumbnailViewthat you want to intercept taps.
EDIT:
In addition, you set the frame of the ThumbnailView to be with size of (0,0).
That means that this view is basically invisible and thus won't intercept touches.
And finally, please don't do:
ThumbnailView* thumbnail = [array objectAtIndex:0];
Instead you can check the count of the array or simply:
ThumbnailView* thumbnail = [array lastObject];

problem with UiImageView.image = nil

.h file
#interface AppViewController : UIViewController {
...
UIImageView *imageViewArray[3][5];// not using any #property for this
...
}
...
#define FOR(j,q) for (int j = 0; j < q; j++)
.m file
ViewDidLoad{
FOR(i,5){
FOR(j,3)
{
image_names[0] = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png",j]];
imageViewArray[j][i] = [[UIImageView alloc] initWithImage: image_names[0]];
CGRect newFrame ;
newFrame = CGRectMake(60+(j*130), 110+(150*i),130,136);
imageViewArray[j][i].frame = newFrame;
[self.view addSubview:imageViewArray[j][i]];
}
}
}
//clear the previous images and call a method to add new
-(IBAction)Change{
FOR(i,5)
FOR(p,3)
imageViewArray[p][i].image = nil;
[self ImageSwitch];
}
-(void)ImageSwitch{
FOR(i,5){
FOR(j,3)
{
image_namesTmp[0] = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png",j+3]];
imageViewArray[j][i] = [[UIImageView alloc] initWithImage: image_namesTmp[0]];
CGRect newFrame ;
newFrame = CGRectMake(60+(j*130), 110+(150*i),130,136);
imageViewArray[j][i].frame = newFrame;
[self.view addSubview:imageViewArray[j][i]];
}
}
}
when i press the button for the first time it works fine(old images get replaced with new ones),but if i do it second time
imageViewArray[p][i].image = nil;
this line wont work and all the previous images still remain there and new images are overlapping with the present ones
In the ImageSwitch method you are always creating new instances of UIImageView.
imageViewArray[j][i] = [[UIImageView alloc] initWithImage: image_namesTmp[0]];
At this point, there already is a reference to UIImageView stored in the variable. You are losing your reference to it and since you alloc/inited it, you will most probably also leak its memory. Moreover, you are adding new UIImageViews to the view hierarchy, but you are not removing the old ones.
Try something like this:
[imageViewArray[j][i] removeFromSuperview];
[imageViewArray[j][i] release];
imageViewArray[j][i] = [[UIImageView alloc] initWithImage: image_namesTmp[0]];
Second time you set your images you don't need to recreate the UIImageView objects. Your ImageSwitch method is better declared as,
-(void)ImageSwitch{
FOR(i,5){
FOR(j,3)
{
imageViewArray[j][i].image = [UIImage imageNamed:[NSString stringWithFormat:#"%d.png",j+3]];
}
}
}
Just changing the images will suffice and that's what you need to do.
You need an NSMutableArray of ImageViews. In your header declare the NSMutableArray:
NSMutableArray *_imageViewArray;
Then in your viewDidLoad method initialize the array and then populate it with your image views.
_imageViewArray = [[NSMutableArray alloc]init];
for (int i =0; i < imageNames; i++) {
UIImageView *tempImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:[imageNames objectAtIndex:i];
[_imageViewArray addObject:tempImageView];
[tempImageView release];
}
So thats the image view array populated, you may do it a different way but thats up to you.
To switch the views over what I would do is like so...
[self.view removeAllSubviews]; // gets rid of all previous subviews.
[self.view addSubview:[_imageViewArray objectAtIndex:3]];// could be any number. generate a random number if you want.
Thats all you would need to do. If you wanted to know which image view was being displauyed the maybe declare an instance of UIImageView in your header called _currentImageView and then you can remove just that image view instead of all subviews.
Hope this helped.