ViewControllers with TextViews in UIPageViewController - objective-c

I was trying to learn UIPageViewControllers and hit an Issue which I couldn't resolve.
This is what I tried to do:
Steps:
I simply created 2 view controllers and a page view controller in
StoryBoard.
Then I added some code to the File's Owner of PageViewController to
behave as a dataSource and delegate to itself.
When I ran, things worked well.
I added some buttons, and text fields to the second view controller.
I ran, worked well.
Now I added a text view to the second view controller and ran. When I tried to write something inside the text view, the page control jittered and moved to first view controller.
Has anyone experience this ever?
#interface AMPageViewController : UIPageViewController <UIPageViewControllerDataSource, UIPageViewControllerDelegate>
#end
The implementation:
#import "AMPageViewController.h"
#interface AMPageViewController ()
{
UIViewController *mainController;
UIViewController* socController;
}
#end
#implementation AMPageViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"MainStoryboard"
bundle: nil];
mainController = (UIViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: #"First"];
socController = (UIViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: #"Second"];
[self setViewControllers:#[mainController]
direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
self.dataSource = self;
self.delegate = self;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
if (viewController == socController )
return mainController;
else return nil;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
if (viewController == mainController )
return socController;
else return nil;
}
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController
{
return 2;
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController
{
return 0;
}
#end
If you want to download and try the project

I've investigated a lot on this problem.
It seems a bug related to the internal (private) UIScrollView of the UIPageViewController.
If you search on StackOverflow you will find a lot of post with this problem and no solutions...
I seems that the UITextView (which is an UIScrollView and, AFAIR, has an internal UIWebView), sends some strange message to it's superviews chain, that makes the private UIScrollView of the UIPageViewController scrolling to the top-left corner.
I would have tried to block this message using method swizzling, but this is probably not ok for AppStore. So I tried other things.
The final solution is very simple: simply, embed your UITextView inside an UIScrollView!
This is a link to your project updated
If you do so, you'll solve the problem!
Try and let me know
EDIT:
How did I arrive to this solution:
An intuition.
A lot of debug and stack traces had make me think that the problem was related to a bug in the "nesting UIScrollView" system and some messages sent from the inner view to its superview.
UITextView inherits from UIScrollView and has inside an UIWebDocumentView (private) which is another UIScrollView. During the debug I saw a lot of messages (private methods) like "relayout superview" sent to the upper UIScrollView's. So, for some reason, the inner scroll view (UIWebDocumentView?) was sending a message/event to it's superview. This message/event (probably because of a bug) was not stopping to the external UITextView, and was forwarded to the UIScrollView handled by UIPageViewController.
Embedding the UITextView inside a simple UIView was not enough, because UIView forward the message to it's superview if it can't handle.
I thought: UIScrollView probably doesn't (otherwise it wouldn't simple to nest UIScrollViews), so I tried and it worked.
This is all a supposition because I stopped inspecting, I will have a more in-depth look this week.

Build target iOS-7.0.
The scrollview trick wasn't working for me. Tried to embed the textview in a scrollview through storyboard and code but no luck.
Simply delaying the call to the textview did it. Not very elegant, but its the only thing I've gotten to work so far.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.textView becomeFirstResponder];
});
}
Tested, working on my iPhone 5 and my ultra-slow iPhone4. Although its totally possible that whatever implementation detail enables the textview to become the responder could take longer than the set time. So keep in mind this isn't exactly bulletproof.
--EDIT--
Well... it's working on my iPhone 4 beater with a delay of 0.0000000000000001

you did not set before and after view controllers and also look in to first responder for socController

Related

UIViewController not calling viewDidLoad & not creating UIView causing crash

I've been at this for a few hours now. I've got several View Controllers in this project and not a single one is causing issues but now all of a sudden this new one is. I even deleted it and made a "Test" View Controller, but no dice. The best I can tell it is not actually creating its view, thus when the view is referenced the app crashes. The test VC has no added or deleted code except for a log statement in the -viewDidLoad method. I am not overriding -loadView. I have tried adding the view to a subview, have tried pushing the VC into the Navigation Controller, I have even tried simply logging test.view. I have tried creating the VC with a NIB and have tried it without one. Absolutely nothing works at all. Any help will be appreciated.
Where VC is being created inside of another VC. The log statment causes the crash. But so does adding as a subview and even pushing into nav controller.
TestViewController *test = [[TestViewController alloc] init];
NSLog(#"test view = ", test.view);
Implementation of TestViewController.
#implementation TestViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(#"view = %#", self.view);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I'd say to double check all the connections from the view. Especially if its been copied or moved as its easy to leave a connection to an old VC
if you are not using ARC in your project then dont check the autolayout box for the nib file. If you are using ARC then the connections of it to the file's owner can be the only issue.
if you use xib,and the items is copied from other xib or storyboard ,make sure the root view is exist,and drag tothe file's owner.

UIGestureRecognizer causing "EXC_BAD_ACCESS" error

Using the GestureRecognizer attached to a view triggers my app to crash with EXC_BAD_ACCESS error. Here's the classes involved
• BoardViewController - Displaying a board (as background) set as rootViewController in the AppDelegate. It instantiates multiple objects of the "TaskViewcontroller".
//BoardViewController.h
#interface BoardViewController : UIViewController {
NSMutableArray* allTaskViews; //for storing taskViews to avoid having them autoreleased
}
//BoardViewController.m - Rootviewcontroller, instantiating TaskViews
- (void)viewDidLoad
{
[super viewDidLoad];
TaskViewController* taskA = [[TaskViewController alloc]init];
[allTaskViews addObject:taskA];
[[self view]addSubview:[taskA view]];
}
• TaskViewController - An indivual box displayed on the board. It should be draggable. Therefore I attached UIPanGestureRecoginzer to its view
- (void)viewDidLoad
{
[super viewDidLoad];
UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(handlePan:)];
[[self view] addGestureRecognizer:panRecognizer];
}
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
NSLog(#"PAN!");
}
The .xib file is a simple view.
All programming with the gesture recognizer I'd prefer to do in code. Any idea how to fix the error causing the app crash?
The method handlePan is on your view controller, not on your view. You should set the target to self:
UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(handlePan:)];
EDIT (in response to the edit of the question) As omz has correctly noted, your TaskViewController gets released upon BoardViewController's viewDidLoad: exit. There are two ways of dealing with it:
Fold the handlePan method into the parent view controller, along with the code of viewDidLoad:, or
Make an instance variable for TaskViewController *taskA, rather than making it a local variable.
This is my way to use Gesture Recognizer. I think this way is easy and with low risk.
At first, you drag and drop Gesture Recognizer into the view.
Then, you wire the Gesture Recognizer icon to code.
Finally, you write code for this IBAction like below:
- (IBAction)handlePan:(id)sender {
NSLog(#"PAN!");
}
You can download this project from GitHub and just run it.
https://github.com/weed/p120812_PanGesture

UIPageViewControllerSpineLocation Delegate Method Not Firing

Major head-scratcher all day on this one :-(
I have an instance of a UIPageViewController that does not appear to be firing the delegate method:
-(UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
I have tried various methods of displaying the UIPageViewController and have settled on a programatic approach (as opposed to a Storyboard one) that appears to be working correctly, with one exception... when rotating the iPad to landscape the spine does not appear mid-point as expected. I simply cannot find out why the delegate method does not get called.
Code Explanation (simplified for example)
Consider three classes as follows:
RootViewController - loaded when the app starts
PageViewController - loaded by RootViewController upon user initiation
PageContentViewController - loaded by PageViewController when pages are needed
Fairly self-explanatory. The RootViewController is loaded by the app upon launch. When the user taps an image within this view controller's view (think magazine cover opening a magazine) it launches the PageViewController as follows:
PageViewController *pvc = [[PageViewController alloc] initWithNibName:#"PageView"
bundle:[NSBundle mainBundle]];
pvc.view.frame = self.view.bounds;
[self.view addSubview:pvc.view];
In the actual app there is animation etc to make the transition all nice, but essentially the PageViewController's view is loaded and takes fullscreen.
PageViewController
This is the workhorse (only relevant methods shown). I have tried various examples from the infinite world of Google and written directly from the Apple docs...
#interface PageViewController : UIViewController <UIPageViewControllerDelegate, UIPageViewControllerDataSource>
#property (nonatomic, strong) UIPageViewController *pageViewController;
#property (nonatomic, strong) NSMutableArray *modelArray;
#end
#implementation TXCategoryController
-(void)viewDidLoad
{
[super viewDidLoad];
// Simple model for demo
self.modelArray = [NSMutableArray alloc] init];
for (int i=1; i<=20; i++)
[self.modelArray addObject:[NSString stringWithFormat:#"Page: %d", i]];
self.pageViewController = [[UIPageViewController alloc]
initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageViewController.delegate = self;
self.pageViewController.dataSource = self;
PageContentViewController *startupVC = [[PageContentViewController alloc] initWithNibName:#"PageContent" bundle:nil];
startupVC.pageLabel = [self.modelArray objectAtIndex:0];
[self.pageViewController setViewControllers:[NSArray arrayWithObject:startupVC]
direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
self.pageViewController.view.frame = self.view.bounds;
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
// Relevant code to add another view...
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
// Relevant code to add another view...
}
-(UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
// Setting a break point in here - never gets called
if (UIInterfaceOrientationIsPortrait(orientation))
{
// Relevant code to create view...
return UIPageViewControllerSpineLocationMin;
}
// Relevant code to create 2 views for side-by-side display and
// set those views using self.pageViewController setViewControllers:
return UIPageViewControllerSpineLocationMid
}
#end
This all works perfectly well as I mentioned earlier. The PageViewController's view gets shown. I can swipe pages left and right in both portrait and landscape and the respective page number appears. However, I don't ever see two pages side-by-side in landscape view. Setting a breakpoint in the spineLocationForInterfaceOrientation delegate method never gets called.
This is such a head-scratcher I have burned out of ideas on how to debug/solve the problem. It almost behaves like the UIPageViewController isn't responding to the orientation changes of the device and therefore isn't firing off the delegate method. However, the view gets resized correctly (but that could be just the UIView autoresizing masks handling that change).
If I create a brand new project with just this code (and appropriate XIb's etc) it works perfectly fine. So something somewhere in my actual project is causing this. I have no idea where to continue looking.
As usual, any and all help would be very much appreciated.
Side Note
I wanted to add the tag 'uipageviewcontrollerspinelocation' but couldn't because it was too long and I didn't have enough reputation (1500 required). I think this is a devious ploy on Apple's part to avoid certain tags in Stackoverflow... ;-)
Finally found the problem. It was something of a red herring in its symptoms, but related just the same.
Putting a break point in the shouldAutorotateToInterfaceOrientation: method was a natural test to see if the UIViewController was even getting a rotation notification. It wasn't which led me to Apple's technical Q&A on the issue: http://developer.apple.com/library/ios/#qa/qa1688/_index.html
The most relevant point in there was:
The view controller's UIView property is embedded inside UIWindow but alongside an additional view controller.
Unfortunately, Apple, in its traditional documentation style, doesn't provide an answer, merely confirmation of the problem. But an answer on Stack Overflow yielded the next clue:
Animate change of view controllers without using navigation controller stack, subviews or modal controllers?
Although my RootViewController was loading the PageViewController, I was doing it as a subview to the main view. This meant I had two UIViewController's in which only the parent would respond to changes.
The solution to get the PageViewController to listen to the orientation changes (thus triggering the associated spine delegate method) was to remove addSubview: and instead present the view controller from RootViewController:
[self presentViewController:pac animated:YES completion:NULL];
Once that was done, the orientation changes were being picked up and the PageViewController was firing the delegate method for spine position. Only one minor detail to consider. If the view was launched in landscape, the view was still displaying portrait until rotated to portrait and back to landscape.
That was easily tweaked by editing viewDidLoad as follows:
PageContentViewController *page1 = [[PageContentViewController alloc] initWithNibName:#"PageContent" bundle:nil];
NSDictionary *pageViewOptions = nil;
NSMutableArray *pagesArray = [NSMutableArray array];
if (IS_IPAD && UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
{
pageViewOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:UIPageViewControllerSpineLocationMid]
forKey:UIPageViewControllerOptionSpineLocationKey];
PageContentViewController *page2 = [[PageContentViewController alloc] initWithNibName:#"PageContent" bundle:nil];
[pagesArray addObject:page1];
[pagesArray addObject:page2];
}
else
{
[pagesArray addObject:page1];
}
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
options:pageViewOptions];
self.pageViewController.delegate = self;
[self.pageViewController setViewControllers:pagesArray
direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:NULL];
Job done and problem solved.

Problems with storyboard

recently I started using storyboard and I've the following situation: I want to set the text of an UILabel from the AppDelegate. So I created an instance of my ViewController
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"MainStoryboard"
bundle: nil];
ViewController *controller = (ViewController*)[mainStoryboard
instantiateViewControllerWithIdentifier: #"mainViewController"];
myViewController = controller;
[window addSubview:myViewController.view];
[window makeKeyAndVisible];
and called the following method from the delegate
- (void) updateParameterLabel:(NSString *)parameter {
NSLog(#"URL-2: %#", parameter);
parameterLabel.text = parameter;
}
But the parameter is not shown in the UI.
Another think, which is kind of strage:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(#"View did Appear");
}
The "View did appear" is logged twice ...
Any hints?
Regards,
Sascha
Setting the text of a UILabel from your application delegate isn't great design. Your view controllers should be managing the content of your views, hence their name. Typically your storyboard is instantiated automatically, and you don't need any of the storyboardWithName et code you've got, assuming you're working with Apple's default templates.
Maybe think about re-architecting your application to follow the 'model-view-controller' pattern more strictly, and also look at how Apple instantiate storyboards automatically (just create a new storyboard project in XCode to see this).
If you still want to make it work, make the UILabel a property of your viewcontroller and set the label by using
In delegate :
- (void) updateParameterLabel:(NSString *)parameter {
NSLog(#"URL-2: %#", parameter);
[myViewController updateParemeter:parameter];
}
In myViewController:
- (void) updateParameterLabel:(NSString *)parameter {
NSLog(#"URL-2: %#", parameter);
parameterLabel.text = parameter;
[self.view setNeedsDisplay];//edit
}
So use the viewController to update your label. Of course you need the label as a property in your viewController
For what I see you are trying to update the label before it appears, so why don't you try calling your updateLabel method in the viewWillAppear, it would be something like this
-(void)viewWillAppear:(BOOL)animated{
[self updateParameterLabel:#"Some Text"];
[super viewWillAppear:YES];
}
And updateParameterLabel has to be implemented in the viewController.

view controller not appearing in iOS 5 project

i started a single view template in Xcode 4.2(recently upgraded to Xcode 4.2 and ios5)
so now i have only one view controller.
I added a new class to the project which is a subclass of UIViewcontroller.
Now in the main controller class viewdidLoad method
- (void)viewDidLoad
{
// Override point for customization after application launch.
[super viewDidLoad];
[self presentQuizcontroller];
}
-(void) presentQuizcontroller
{
_QuizController = [[[Quiz alloc] initWithNibName:#"Quiz" bundle:nil] autorelease];
_QuizController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:_QuizController animated:YES]; // Do any additional setup after loading the view, typically from a nib.
}
the problem is in my Quiz class
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
the initWithNibName method does get called(i checked by using breakpoint) but it doesn't passes the condition of if(self) . and hence the view don't appears.
Any ideas?
Edit
After the first answer i tried this way too
- (void)viewDidLoad
{
// Override point for customization after application launch.
[super viewDidLoad];
}
-(void) presentQuizcontroller
{
_QuizController = [[[Quiz alloc] initWithNibName:#"Quiz" bundle:nil] autorelease];
_QuizController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:_QuizController animated:YES]; // Do any additional setup after loading the view, typically from a nib.
}
-(void) awakeFromNib
{
[self presentQuizcontroller];
}
same thing Quiz.m initwithnib name method does not passes the condition if(self).
I think you need to use awakefromnib.
Here is the Link for another StackOverflow post if you want to read more.
PresentModalViewController is depreciated, I think you should now use presentViewController instead of it.
Are you sure that "Quiz" is the name of your file? That string should be same as the name of your xib file, namely something like "QuizController" or "QuizViewController"
Make sure the xib file is properly connected to header/implementation files by checking:
Owner of the xib file should be set as the viewController
View on the xib file (the one above all if you have multiple views) should be connected to viewControllers view.