I have seen many of the posts on this site as well as many more on Google, and I am stuck on what I am sure is something easy. I am new to iOS, and I have most likely been reading the other posts incorrectly. I am trying to learn and write my own code with my own logic and attempts, so mine looks a good deal different than the others I have found... which is why it doesn't work I am sure!
I am trying to get a picture show using swipe from right to left, but I want the next picture to be pulled over and slide into place, instead of the instant switch I have done here. Based on many recommendations, I am trying to use a UIScrollView. I can't get anything to load and the app crashes on the last line of loadImages. I have debugged but can't seem to figure out why it is not showing the subView.
Here is my viewDidLoad:
[super viewDidLoad];
// Do any additional setup after loading the view.
i = 0;
//add UIPanGestureRecognizer
UIPanGestureRecognizer *aPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(loadImages)];
[aPan setMaximumNumberOfTouches:1];
[aPan setMinimumNumberOfTouches:1];
[self.view addGestureRecognizer:aPan];
_PhotoBundle = [[NSBundle mainBundle] pathsForResourcesOfType:#".jpg"inDirectory:#"Otter_Images"];
_PhotoArray = [[NSMutableArray alloc] initWithCapacity:_PhotoBundle.count];
for (NSString* path in _PhotoBundle)
{
[_PhotoArray addObject:[UIImage imageWithContentsOfFile:path]];
}
[self loadImages];
Here is my loadImages:
-(void)loadImages
{
NSLog(#"in loadImages");
_currentImage = [_PhotoArray objectAtIndex:i];
_nextImage = [_PhotoArray objectAtIndex:i + 1];
_prevImage = [_PhotoArray objectAtIndex:i -1];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
[scrollView setScrollEnabled:YES];
[scrollView setClipsToBounds:YES];
if (i <= _PhotoArray.count)
{
[scrollView addSubview:_currentImage]; ////crash!!!!
}
else
{
_currentImage = [_PhotoArray objectAtIndex:0];
[scrollView addSubview:_currentImage]; /// Crash!!!!
}
NSLog(#"end of loadImages");
}
I have left off functionality until I can get one image loaded. I will then add the functionality for the slide.... I hope I am approaching this right.
Thank you very much for any help!!
edit:
Here is my interface in my .m that sets up the ImageViews:
#interface ScrollViewViewController ()
#property (nonatomic, retain) NSArray *PhotoBundle;
#property (nonatomic, retain) NSMutableArray *PhotoArray;
#property (nonatomic, retain) UIImageView *currentImage;
#property (nonatomic, retain) UIImageView *nextImage;
#property (nonatomic, retain) UIImageView *prevImage;
#end
You are adding UIImage objects as subviews. You can't do this. You have to make a UIImageView first - only UIView subclasses can be added as subviews.
Making an image view is simple - you can alloc/initWithImage: and pass in your image object. You'll need to adjust the frames of each image view otherwise they'll all be on top of each other.
Additionally, you don't need a pan gesture recogniser if you're using a scroll view. The scroll view handles this for you.
Related
I'm trying to create a basic project that uses labels and gesture recognition but am having a little difficulty. I created an interface of 4 UILabels positioned vertically along the center of the app screen. Looks something like:
Question
Next Question
Answer
Show Answer
...just 4 labels, positioned one after the next. I make connections from Interface Builder to my ViewController.h file to create IBOutlet properties for each of the labels. Simple enough. I then go ahead and write all the implementation code in the .m file (seen below). The only issue is when the app runs, all that is displayed is four positioned labels with the default "Label" text from Interface Builder. The gesture recognizers I added to two of the labels do not seem to be connected/triggering either.
Hoping someone could shed a little light on the issue for me. What started as a simple exercise is driving me a little mad.
Here's my Viewcontroller.h file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) IBOutlet UILabel *labelQuestion;
#property (nonatomic, strong) IBOutlet UILabel *labelNextQuestion;
#property (nonatomic, strong) IBOutlet UILabel *labelAnswer;
#property (nonatomic, strong) IBOutlet UILabel *labelShowAnser;
#end
And here's my Viewcontroller.m file:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, copy) NSArray *arrayQuestions;
#property (nonatomic, copy) NSArray *arrayAnswers;
#property (assign) int incrementer;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// First create the datasource arrays with five elements each
self.arrayQuestions = [[NSArray alloc] init];
self.arrayQuestions = [NSArray arrayWithObjects:#"Who am I?", #"Who are you?", #"Where are we?", #"What's going on?", #"Why is this happening?", nil];
self.arrayAnswers = [[NSArray alloc] init];
self.arrayAnswers = [NSArray arrayWithObjects:#"Damian", #"Dmitri", #"I don't know.", #"You tell me.", #"I have no clue", nil];
// Reset the incrementer's value
self.incrementer = 0;
// Next configure the labels
self.labelQuestion = [[UILabel alloc] init];
self.labelQuestion.text = [self.arrayQuestions objectAtIndex:self.incrementer];
self.labelNextQuestion = [[UILabel alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(nextQuestionLabelPressed)];
[tap setNumberOfTapsRequired:1];
[self.labelNextQuestion addGestureRecognizer:tap];
self.labelNextQuestion.text = #"Show next question";
self.labelAnswer = [[UILabel alloc] init];
self.labelAnswer.text = #"?????";
self.labelShowAnser = [[UILabel alloc] init];
self.labelShowAnser.userInteractionEnabled = YES;
UITapGestureRecognizer *tapp = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showAnswerLabelPressed)];
[tapp setNumberOfTapsRequired:1];
[self.labelShowAnser addGestureRecognizer:tapp];
self.labelShowAnser.text = #"Show answer";
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)nextQuestionLabelPressed {
self.incrementer++;
self.labelQuestion.text = [self.arrayQuestions objectAtIndex:self.incrementer];
self.labelAnswer.text = #"?????";
}
- (void)showAnswerLabelPressed {
self.labelAnswer.text = [self.arrayAnswers objectAtIndex:self.incrementer];
}
#end
Let's say you've connected a label from the storyboard to self.labelQuestion. So far so good. When you launch, self.labelQuestion points to the label from the storyboard, which is the one that you see in the visible interface of the running app.
But then you say:
self.labelQuestion = [[UILabel alloc] init];
That disconnects the outlet and replaces the value of that variable (self.labelQuestion) with a new blank label! So anything you now do to labelQuestion cannot possibly affect the one from the storyboard, as you have broken the connection.
You do that for all four labels, so you have smashed all four outlets into dust. Thus, your other code has no effect on the visible labels, which come from the storyboard.
Just delete all four [[UILabel alloc] init] lines, and all will be well.
I have a view controller with a few buttons, labels and 2 views. One view is a background. The other is a puzzle on top of it. Everything is in perfect working order. I know how to randomly create the puzzles keeping just one background. What I want to do is hit a button and have a new puzzle with its matching background. I want all other functions on the page to stay the same. Just a new puzzle with it's matching background. Any help would be greatly appreciated.
I'll leave the details of the implementation for you to fill in.
You need to be able to correlate your views. You can do this with strictly-managed arrays or with simple composition objects or with direct relationship.
strictly-managed arrays
NSArray *puzzles = #[/*...*/];
NSArray *backgrounds = #[/*...*/];
- (IBAction)changePuzzle {
NSUInteger index = arc4random_uniform([puzzles count]);
UIView *puzzleView = puzzles[index];
UIView *backgroundView = backgrounds[index];
// Update UI with puzzleView and backgroundView
}
simple composition object
#interface MatchedView : NSObject
#property (strong) UIView *puzzle;
#property (strong) UIView *background;
#end
NSArray *matchedViews = #[/*...*/];
- (IBAction)changePuzzle {
NSUInteger index = arc4random_uniform([matchedViews count]);
UIView *puzzleView = [matchedView[index] puzzleView];
UIView *backgroundView = [matchedView[index] backgroundView];
// Update UI with puzzleView and backgroundView
}
direct relationship
#interface PuzzleView : UIView
#property (strong) UIView *backgroundView;
/* ... */
#end
NSArray *puzzleViews = #[/*...*/];
- (IBAction)changePuzzle {
NSUInteger index = arc4random_uniform([puzzleViews count]);
PuzzleView *puzzleView = puzzleViews[index];
UIView *backgroundView = [puzzleView backgroundView];
// Update UI with puzzleView and backgroundView
}
Make those IBOutlets as you see fit. You can replace the array in any of those cases with any other way that you have to look up the views you want to randomly choose among (i.e. using tag).
I am working on the UIPopover and in one of the example I found that the Popover object is
created but then the object is assigned to the property of the Viewcontroller.
UIPopoverController* aPopover = [[UIPopoverController alloc] initWithContentViewController:content];
self.popoverController = aPopover;
What is the merit in such assignment and any reason for not assigning object to the property directly?
There is no "merit" in it. Saying
self.popoverController =
[[UIPopoverController alloc] initWithContentViewController:content];
would be absolutely equivalent.
On the other hand there is nothing wrong with using a temporary variable (aPopover) as shown in your example. It's just a name (a pointer); there is no significant waste of space or time. Moreover, saying self.popoverController repeatedly (either to set or to get its value) is to be avoided, because this is a method call - you are passing through the setter method or getter method (which may be synthesized, may have side effects, and does in fact take some extra time). Thus, when there is much configuration to be done (for example), it is best to do it as shown in your example:
UIPopoverController* aPopover =
[[UIPopoverController alloc] initWithContentViewController:content];
// lots of configuration here, using the local automatic variable aPopover...
// ...and then, only when it is all done, call the setter:
self.popoverController = aPopover;
The only reason for that is that you probably read this in a tutorial somewhere. And the author did it for readability for beginners. You could absolutely use:
self.popoverController = [[UIPopoverController alloc] initWithContentViewController:content];
All depending on how familiar you are with programming in general and how readable you want your code to be.
I agree with the others that, in this case, the assigning of the popover controller to a local variable before later assigning it to a class property is largely a stylistic matter. But this is only the case because you are keeping a strong reference to that popover controller. There are other situations where you have weak properties, in which this local variable pattern is critical.
For example, let's assume that we have a bunch of controls that we're going to add to our view controller's view programmatically:
#property (nonatomic, strong) UIView *containerView;
#property (nonatomic, strong) UILabel *usernameLabel;
#property (nonatomic, strong) UILabel *emailLabel;
// and more labels
When you want to add these to your view controller's view, you could do something like:
- (void)addSubviewsAtPoint:(CGPoint)location
{
self.containerView = [[UIView alloc] initWithFrame:[self frameForContainer:location]];
[self.view addSubview:self.containerView];
self.usernameLabel = [[UILabel alloc] initWithFrame:[self frameForUsernameLabel]];
[self.containerView addSubview:self.usernameLabel];
self.usernameLabel.text = self.username;
self.emailLabel = [[UILabel alloc] initWithFrame:[self frameForEmailLabel]];
[self.containerView addSubview:self.emailLabel];
self.emailLabel.text = self.email;
// etc.
}
But it also means that when you remove the subviews, you not only have to remove the container view from your view hierarchy, but you also have to remember to nil all of the properties for all of those subviews:
- (void)removeSubviews
{
[self.containerView removeFromSuperview];
self.containerView = nil;
self.emailLabel = nil;
self.usernameLabel = nil;
// etc.
}
This introduces a maintenance issue, that every time you add a new control via addSubviewsAtPoint, that you also have to remember to add it to removeSubviews, too, or else you might be hanging on to the control well after you've removed it from the screen.
To simplify your life, you might make all of these properties weak (with the intuition being that it's the view that owns these subviews, not the view controller):
#property (nonatomic, weak) UIView *containerView;
#property (nonatomic, weak) UILabel *usernameLabel;
#property (nonatomic, weak) UILabel *emailLabel;
// etc.
But now, using ARC, your addSubviewsAtPoint no longer works, because when you assign an object to a weak property, if there are no other strong references, it will be immediately become nil:
self.containerView = [[UIView alloc] initWithFrame:[self frameForContainer:location]];
[self.view addSubview:self.containerView]; // FAIL!!! self.containerView will be nil!
So, instead, we employ that local variable pattern of your question to ensure that the controls are not prematurely deallocated while we're adding them to our view:
- (void)addSubviewsAtPoint:(CGPoint)location
{
UIView *containerView = [[UIView alloc] initWithFrame:[self frameForContainer:location]];
[self.view addSubview:containerView];
self.containerView = containerView;
UILabel *usernameLabel = [[UILabel alloc] initWithFrame:[self frameForUsernameLabel]];
[containerView addSubview:usernameLabel];
usernameLabel.text = self.username;
self.usernameLabel = usernameLabel;
UILabel *emailLabel = [[UILabel alloc] initWithFrame:[self frameForEmailLabel]];
[containerView addSubview:emailLabel];
emailLabel.text = self.email;
self.emailLabel = emailLabel;
// etc.
}
And, as a result, because we're using weak properties, our removal of those subviews is now much simpler, as we don't have to nil all of those properties when we remove the containerView from our view controller's view:
- (void)removeSubviews
{
[self.containerView removeFromSuperview];
// because all of those `containerView` subviews were `weak`,
// we don't have to manually `nil` them
}
I'm having a main view controller containing a UIScrollView called containerScrollView. This scrollview has on each page another scrollview with the size of the screen containing two view controllers: MessagesViewController and InfoViewController. Here's a schema.
The personScrollView in the containerScrollView works fine but the problem is in the adding of the two view controllers' view to the personScrollView.
#property (nonatomic, retain) MessagesViewController *matchesVC;
#property (nonatomic, retain) InfoViewController *standingsVC;
for (int i = 0; i < 3; i++) {
UIScrollView *personScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(i*320, 0, 320, self.containerScrollView.frame.size.height)];
NSArray *colors = #[[UIColor blueColor], [UIColor orangeColor], [UIColor greenColor]];
[personScrollView setBackgroundColor:[y objectAtIndex:i]];
[personScrollView setPagingEnabled:YES];
[personScrollView setContentSize:CGSizeMake(self.view.frame.size.width * 2, personScrollView)];
[self.containerScrollView addSubview:personScrollView];
/* Populate the scrollview */
// Messages
if (self.messagesVC == nil)
{
self.messagesVC = [[MessagesViewController alloc] init];
[self.messagesVC setFrame:CGRectMake(0, 0, 320, self.containerScrollView.frame.size.height)];
}
[personScrollView addSubview:self.messagesVC.view];
// Info
if (self.infoVC == nil)
{
self.infoVC = [[InfoViewController alloc] init];
[self.infoVC setFrame:CGRectMake(320, 0, 320, self.containerScrollView.frame.size.height)];
}
[personScrollView addSubview:self.infoVC.view];
}
[self.containerScrollView setContentSize:CGSizeMake(320*3, self.containerScrollView.frame.size.height)];
The problem is that the two view controllers (messages and info) only get added once, and to the last personScrollView of containerScrollView.
How to get the view controllers added to all of my personScrollViews? Something wrong with the property declaration?
I have read something about this abusing view controllers, but this is the only solution. There is really a lot of code in the two view controllers and I can't add it to my rootviewcontroller.
The problem is with your understanding of the difference between view controllers and views. You need to read up on Creating Custom Container View Controllers.
Apple doc says:
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
You create your controllers once, but you want to add theirs views three times, to three different parent views. You can't do that.
I ended up creating multiple instances of my view controllers and storing them in an array. Not a great solution, but the best I could find.
#property (strong, nonatomic) MessagesViewController *messagesVC1;
#property (strong, nonatomic) MessagesViewController *messagesVC2;
#property (strong, nonatomic) MessagesViewController *messagesVC3;
#property (strong, nonatomic) MessagesViewController *messagesVC4;
#property (strong, nonatomic) MessagesViewController *messagesVC5;
#property (strong, nonatomic) MessagesViewController *messagesVC6;
self.messagesVC1 = [[MessagesViewController alloc] initWithData:data];
self.messagesVC2 = [[MessagesViewController alloc] initWithData:data];
self.messagesVC3 = [[MessagesViewController alloc] initWithData:data];
self.messagesVC4 = [[MessagesViewController alloc] initWithData:data];
self.messagesVC5 = [[MessagesViewController alloc] initWithData:data];
self.messagesVC6 = [[MessagesViewController alloc] initWithData:data];
self.messagesVCArray = #[self.messagesVC1, self.messagesVC2, self.messagesVC3, self.messagesVC4, self.messagesVC5, self.messagesVC6];
MessagesViewController *messagesVC = [self.messagesVCArray objectAtIndex:i];
[messagesVC setFrame:CGRectMake(0, 0, 320, leagueScrollView.frame.size.height)];
[leagueScrollView addSubview:messagesVC.view];
Basically, I have a UIViewController with a xib built for holding content in a UIScrollView. this gets populated from an RSS feed. this works as expected. I want a tap on the UIView that the view controller owns to respond to a tap and continue on its way. however, a tap crashes the app with the "unrecognized selector sent to instance" error. I really have no clue what's going on.
The .h file of the xib's view controller looks like this:
#property (nonatomic,retain) IBOutlet UIImageView *article_image;
#property (nonatomic,retain) IBOutlet UILabel *article_title;
#property (nonatomic,retain) IBOutlet UILabel *article_date;
#property (nonatomic,retain) IBOutlet UIActivityIndicatorView *spinner;
#property (nonatomic,retain) NSString *preview_image;
- (void) loadPreviewImage;
Then the .m file looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGesture)];
singleTap.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:singleTap];
self.view.layer.shadowColor = [UIColor blackColor].CGColor;
self.view.layer.shadowOpacity = 0.6;
self.view.layer.shadowRadius = 1.5;
self.view.layer.shadowOffset = CGSizeMake(0, 0);
}
- (void) singleTapGesture:(UITapGestureRecognizer *)gesture {
NSLog(#"TAPPED!");
}
Even if I put just a simple roundrectbutton in the xib and attach it to an IBAction - it crashes, so I'm figuring there's something wrong with how my xib is set up, but I have no clue as to what. those properties in the .h get populated just fine from the VC that holds the scrollview, so the xib obviously knows the file it's associated with, so I just can't figure out why it's crashing and throwing that error on a tap.
The fix is this:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGesture:)];
notice the : at the end of the selector.
Indeed, your action method signature is:
- (void) singleTapGesture:(UITapGestureRecognizer *)gesture;
while
#selector(singleTapGesture)
would rather identify:
- (void) singleTapGesture;
Hope this clarifies the issue.
well, i never really figured out exactly what was causing the crash - so i wound adding the gesture recognizer to the objects into the loop that builds them and all works great. not how i'd like to have done it (was trying to keep it in the object's class definition) but whatever. perhaps this will help someone else.