What I m Thinking to do is ? there is one MainViewController in which there are two UIViews one loaded UITableViewController and other UIPageViewController.
In TableViewController, there are list of pdf's names. But when i click of the pdf list, it does not loads the PageViewController with new pdf in context.
Pdf file names are store in .plist file, Pdfs are fetch from NSBundle or NSDocumentDirectory
In TableViewController
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Play *play = (Play *)[[self.sectionInfoArray objectAtIndex:indexPath.section] play];
Quotation *qute = [play.Details objectAtIndex:indexPath.row];
if ([qute.Key isEqualToString:#"ABC"])
{
AppDelegate *app = [[UIApplication sharedApplication]delegate];
app.strpdfname = qute.Value;
MiddleViewController *mid = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
ContentViewController *cvc = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
[mid viewDidLoad];
[cvc viewDidLoad];
}
else
{
MainViewController *vc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[vc viewDidLoad];
}
}
In PageViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.modelArray = [[NSMutableArray alloc] init];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
NSURL *targetURL = [NSURL fileURLWithPath:path];
originalPDF = CGPDFDocumentCreateWithURL((__bridge CFURLRef)targetURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(originalPDF);
for (int index = 0; index < numberOfPages ; index++)
{
[self.modelArray addObject:[NSString stringWithFormat:#"%d",index]];
}
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageViewController.delegate = self;
self.pageViewController.dataSource = self;
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
contentViewController.labelContents = [self.modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
CGRect pageViewRect = self.view.frame;
pageViewRect = CGRectInset(pageViewRect, 0.0, 0.0);
self.pageViewController.view.frame = pageViewRect;
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == 0)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex - 1];
return contentViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == self.modelArray.count-1)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex + 1];
return contentViewController;
}
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];
self.pageViewController.doubleSided = NO;
return UIPageViewControllerSpineLocationMin;
}
In ContentViewController of PageViewController
-(UIImage*) imageFromPDF:(CGPDFDocumentRef)pdf withPageNumber:(NSUInteger)pageNumber withScale:(CGFloat)scale
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf,pageNumber);
CGRect tmpRect = CGPDFPageGetBoxRect(pdfPage,kCGPDFMediaBox);
CGRect rect = CGRectMake(tmpRect.origin.x,tmpRect.origin.y,tmpRect.size.width*scale,tmpRect.size.height*scale);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context,-50,rect.size.height-30);
CGContextScaleCTM(context,scale,-scale);
CGContextDrawPDFPage(context,pdfPage);
UIImage* pdfImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return pdfImage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
i = [labelContents intValue];
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
if (i!=0)
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path]);
UIImage *img = [[UIImage alloc] init];
img = [self imageFromPDF:pdf withPageNumber:i withScale:1];
UIImageView *imgview1 = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgview1];
}
else
{
UIImage *imgmain = [UIImage imageNamed:#"Diary4.png"];
UIImageView *imgvmain = [[UIImageView alloc] initWithImage:imgmain];
imgvmain.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y,580,self.view.frame.size.height);
[self.view addSubview:imgvmain];
}
}
In MainViewController
-(void)viewDidload
{
leftView = [[UIView alloc] initWithFrame:CGRectMake(5,25, 200,715)];
leftView.backgroundColor = [UIColor clearColor];
tvc = [[TableViewController alloc] initWithStyle:UITableViewStylePlain];
tvc.plays = self.plays;
tvc.view.frame = leftView.frame;
leftView.clipsToBounds = YES;
[leftView addSubview:tvc.view];
[self.view addSubview:leftView];
middleView = [[UIView alloc] initWithFrame:CGRectMake(107, 30, 575, 670)];
mvc = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
[mvc.view setFrame:middleView.frame];
[middleView addSubview:mvc.view];
[self.view addSubview:middleView];
}
As there is no reload data method for UIPageViewController. I was using UIPageViewController in UIViewController instead of that I use UINavigationController in which the UIPageViewController can be reloaded with dynamic data.So on click of UITableViewController, data is sends to UINavigationController-->UIPageViewController. This has solved the above issue.
Related
So I have a view pager that is suppose to allow users to slide through photos the way a user would expect to slide through a album of photos , but the issue comes in when a user slides around and trys to press the "share" button in the navigation bar. It works fine if a user just opens a photo from the album and never trys to slide right or left , but if they do try to slide in either direction and then try to save the photo they have slid to it returns the photo after the photo the user is currently viewing. Ive eliminated this down to something having to do with viewControllerBeforeViewController and viewControllerAfterViewController being called AFTER the current viewcontroller s callehere is my class:
#import "APPChildViewController.h"
#import "CommentsViewController.h"
#import "ViewPhotosPagerVC.h"
#interface ViewPhotosPagerVC ()
#end
#implementation ViewPhotosPagerVC
- (void)viewDidLoad {
[super viewDidLoad];
// [self.navigationController setNavigationBarHidden:YES animated:YES];
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageController.dataSource = self;
[[self.pageController view] setFrame:CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
CommentsViewController *initialViewController = [self viewControllerAtIndex:0];
NSDictionary *dict =[_photoArray objectAtIndex:_startingIndex];
NSLog(#"DICT:%#",dict);
NSString *msg_id=[dict objectForKey:#"msg_id"];
NSLog(#"MSG_ID:%#",msg_id);
initialViewController.msg_id=msg_id;
initialViewController.navItem=self.navigationItem;
initialViewController.delegate=self;
initialViewController.theIndex=_startingIndex;
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:self.pageController];
[[self view] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CommentsViewController *)viewControllerAtIndex:(NSUInteger)index {
NSLog(#"CommentVC_INDEX:%zd",index);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.navItem=self.navigationItem;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSLog(#"BEFORE_PAGEVIEWCONTROL_CALLED");
NSUInteger index = [(CommentsViewController *)viewController theIndex];
if (index == 0) {
NSInteger newIndex=_photoArray.count;
newIndex--;
return [self viewControllerAtIndex:newIndex];
}
// Decrease the index by 1 to return
index--;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
NSLog(#"AFTER_PAGEVIEWCONTROL_CALLED");
NSUInteger index = [(CommentsViewController *)viewController theIndex];
index++;
if(_photoArray.count<=index){
index=0;
}
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)sharePhoto:(UIImage *)shareImage andText:(NSString *)shareText withDict:(NSDictionary *)dict{
//NSLog(#"SHARE_IMG_UPDATE_DICT:%#",dict);
NSString *ALBUM_ID= [dict objectForKey:#"ALBUM_ID"];
NSString *combinedShareText;
if(![ALBUM_ID isEqualToString:#"0"]){
NSArray *album_array=[dict objectForKey:#"album_info"];
NSDictionary *album_dict=[album_array objectAtIndex:0];
//NSLog(#"ALBUM_DICT:%#",album_dict);
NSString *album_title=[album_dict objectForKey:#"title"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *first_name= [defaults objectForKey:#"first_name"];
NSString *album_photo_count=[dict objectForKey:#"album_img_count"];
combinedShareText= [NSString stringWithFormat:#"%# shared a photo w. you from the event album:%#(%# photos) ~view the rest of this album on for IOS",first_name, album_title,album_photo_count];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
}else{
NSString *first_name=[dict objectForKey:#"first_name"];
NSString *last_name=[dict objectForKey:#"last_name"];
NSString *message =[dict objectForKey:#"message"];
NSString *created_string=[dict objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
combinedShareText= [NSString stringWithFormat:#"'%#'~ posted by %# %# %# | You'll thank me later: www.buhz.com",message,first_name,last_name,ago];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
}
if(![ALBUM_ID isEqualToString:#"0"]){
UIImage *backgroundImage = shareImage;
UIImage *watermarkImage = [UIImage imageNamed:#"ios_watermark_logo.png"];
UIGraphicsBeginImageContext(backgroundImage.size);
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
[watermarkImage drawInRect:CGRectMake(backgroundImage.size.width - 240, backgroundImage.size.height - 110, 230, 100)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText,result]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}else{
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText,shareImage]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
}
-(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
NSMutableAttributedString *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#",text]];
// text color
[textStyle addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, textStyle.length)];
// text font
[textStyle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, textStyle.length)];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width-(point.x*2), image.size.height);
[[UIColor whiteColor] set];
// add text onto the image
[textStyle drawInRect:CGRectIntegral(rect)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)shareUpdate:(NSString *)shareText withDict:(NSDictionary *)dict{
NSLog(#"SHARE_TEXT_UPDATE_DICT:%#",dict);
NSString *first_name=[dict objectForKey:#"first_name"];
NSString *last_name=[dict objectForKey:#"last_name"];
NSString *message =[dict objectForKey:#"message"];
NSString *created_string=[dict objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
NSString *combinedShareText= [NSString stringWithFormat:#"'%#'~ posted by %# %# %# | Join me on www..com",message,first_name,last_name,ago];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
#end
In my app when I visit certain view controllers and touch the Back button in the navigation bar, the navigation title of the resulting viewcontroller looks to be coming from the upper left corner and it looks ugly.
A picture of such an instance is shown below.
I have set the titles programatically.
Can somebody please tell me why this is happening and how I could fix it? Thanks in advance.
Here is my code:
ViewController B
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,120,45)] ;
label.textColor = COLOR_TEXT_NAVIGATION_BAR_COLOR;
label.backgroundColor = [UIColor clearColor];
label.font = FONT_NAVIGATION_TITLE_BAR;
label.text = [NSString stringWithFormat:PAGE_TITLE_ADD_SERVICE_PROVIDER];
self.navigationItem.titleView = label;
[label sizeToFit];
UIButton *homeButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
[homeButton setImage:[UIImage imageNamed:IMG_HOME_MENU_BUTTON] forState:UIControlStateNormal];
[homeButton addTarget:self action:#selector(homeMenuAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];
accNumTextFiled.delegate=self;
nameTextFiled.text = addPayee.providerName;
payLimitTextFiled.text = [NSString stringWithFormat:#"%9.2f", addPayee.paymentLimit];//[NSString stringWithFormat:#"%f",addPayee.paymentLimit];
descTextFiled.text = addPayee.description;
catTextFiled.text = addPayee.maincategory;
subCatTextFiled.text = addPayee.subcategory;
accNumTextFiled.text = addPayee.paymentAccountNumber;
[accNumTextFiled setKeyboardType:UIKeyboardTypeNumberPad];
[self labelCss];
scrollView.contentSize=CGSizeMake(320,450);
}
ViewController A
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = COLOR_BG_INNER_PAGE_COLOR;
NSArray *mappingObjArray1 = #[#"providerName",#"description",#"paymentLimit",#"providerCode",#"maincategory",#"subcategory"];
NSDictionary *queryParams = #{};
commonRestDataMapping = nil;
commonRestDataMapping = [[CommonRestDataMapping alloc] init];
commonRestDataMapping.restDataMappingDelegate = self;
commonRestDataMapping.servicePath = REST_WEB_SERVICE_ADD_PAYEE_LIST;
commonRestDataMapping.mappingObjArray = mappingObjArray1;
commonRestDataMapping.mappingClassString = #"AddPayee";
commonRestDataMapping.mappingKeyPath = #"data";
commonRestDataMapping.mappingQueryParams = queryParams;
[commonRestDataMapping configureRestKit];
[commonRestDataMapping loadDataArray];
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone;
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[super createNavigationBar:USER_ACCOUNT_PAGE];
[super setNavihationTitle:PAGE_TITLE_ADD_PAYEE];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//WEB service data initilization
[[WebServiceUrl getSharedInstance] dataiInitialize];
[GMSServices provideAPIKey:#"AIzaSyCBfhnMtcmdhJaaqff72PlvJIjBTZpfSu4"];
NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString* dbPath = [docPath stringByAppendingPathComponent:#"datadb.sqlite"];
NSFileManager *fm = [NSFileManager defaultManager];
// Check if the database is existed.
if(![fm fileExistsAtPath:dbPath])
{
// If database is not existed, copy from the database template in the bundle
NSString* dbTemplatePath = [[NSBundle mainBundle] pathForResource:#"datadb" ofType:#"sqlite"];
NSError* error = nil;
[fm copyItemAtPath:dbTemplatePath toPath:dbPath error:&error];
if(error){
NSLog(#"can't copy db.");
} else{
NSLog(#" copy db.");
}
} else {
NSLog(#" db exsists");
}
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
UIView *addStatusBar = [[UIView alloc] init];
addStatusBar.frame = CGRectMake(0, 0, 1024, 20);
addStatusBar.backgroundColor = [UIColor blackColor]; //change this to match your navigation bar
[self.window.rootViewController.view addSubview:addStatusBar];
}
homeViewController = [[HomeViewController alloc] initWithNibName:#"HomeViewController" bundle:nil];
UINavigationController *myNav1=[[UINavigationController alloc] initWithRootViewController:homeViewController];
UIImage *navBackgroundImg = [UIImage imageNamed:#"aa1.png"];
[myNav1.navigationBar setBackgroundImage:navBackgroundImg forBarMetrics:UIBarMetricsDefault];//iOS 5 only
// Override point for customization after application launch.
self.viewController = myNav1;
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)transitionToViewController:(UIViewController *)viewController
withTransition:(UIViewAnimationOptions)transition
{
[UIView transitionFromView:self.window.rootViewController.view
toView:viewController.view
duration:0.35f
options:transition
completion:^(BOOL finished){
self.window.rootViewController = viewController;
}];
}
First off: My project is ARC enabled and I'm using storyboard.
I have a view controller that pushes a segue (modal),
[self performSegueWithIdentifier: #"goInitialSettings" sender: self];
there i'm setting some parameters and store them. When the parameters are stored (true a button tap), the app should return to the original viewcontroller.
This i am doing with this command:
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
I'm noticing that the viewcontroller that i dismiss, never deallocs. How does this come?
I'm adding the code of the 'presented viewcontroller' below:
#interface CenterChoiceController ()
{
UIView* _titleBackground;
UILabel* _lblTitle;
UIButton* _btnGaVerder;
UIPickerView* _myPickerView;
NSArray* _centers;
UILabel* _adresLine;
UILabel* _cityLine;
MKPointAnnotation* _point;
MKMapView* _mapView;
UIActivityIndicatorView* _indicator;
UIAlertView* _alert;
GCenter* _center;
DataManager* _dm;
}
#end
#implementation CenterChoiceController
-(void)dealloc
{
NSLog(#"Centerchoice deallocs");
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_mapView = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_dm = [[DataManager alloc]init];
if([_dm hasConnectivity])
{
[_dm fetchCentersForController:self];
}
else
{
[self pushErrorMessage:NSLocalizedString(#"nointernetconnection", nil)];
}
CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];
_titleBackground = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_titleBackground.backgroundColor = [GColor blueColor];
[self.view addSubview:_titleBackground];
_lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, 44)];
_lblTitle.textAlignment = NSTextAlignmentRight;
_lblTitle.textColor = [GColor whiteColor];
_lblTitle.text = NSLocalizedString(#"bioscoopkeuze", nil);
[self.view addSubview:_lblTitle];
_btnGaVerder = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 54, self.view.frame.size.width, 54)];
[_btnGaVerder setTitle:NSLocalizedString(#"gaverder", nil) forState:UIControlStateNormal];
_btnGaVerder.titleLabel.font = [_btnGaVerder.titleLabel.font fontWithSize:12];
_btnGaVerder.backgroundColor = [GColor blueColor];
[_btnGaVerder setTitleColor:[GColor whiteColor] forState:UIControlStateNormal];
[_btnGaVerder setShowsTouchWhenHighlighted:YES];
[_btnGaVerder addTarget:self action:#selector(gaVerder) forControlEvents:UIControlEventTouchUpInside];
_myPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 200)];
}
-(void)showLoading
{
NSLog(#"shows loading");
_indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint cntr = self.view.center;
_indicator.center = cntr;
[_indicator startAnimating];
[self.view addSubview:_indicator];
}
-(void)hideLoading
{
NSLog(#"hides loading");
[_indicator removeFromSuperview];
_indicator = nil;
}
-(void)pushData:(NSArray *)data
{
[self.view addSubview:_btnGaVerder];
[self.view addSubview:_myPickerView];
_centers = data;
_myPickerView.delegate = self;
_myPickerView.dataSource = self;
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.chosenCenter = [_centers objectAtIndex:0];
settings.loadedCenter = [_centers objectAtIndex:0];
_center = settings.chosenCenter;
settings.notificationsEnabled = YES;
[self changeAddressLines];
}
/*if(settings != nil)
{
GCenter* loaded = settings.loadedCenter;
int i = 0;
BOOL found = NO;
while(i < [_centers count] && !found)
{
GCenter* center = (GCenter*)[_centers objectAtIndex:i];
if(settings.loadedCenter.iD == center.iD)
{
_center = center;
settings.chosenCenter = center;
[_dm storeSettings:settings];
found = YES;
}
i++;
}
//[self.myPickerView selectRow:i-1 inComponent:0 animated:NO];
loaded = nil;
[self changeAddressLines];
}
*/
}
-(void) pushErrorMessage: (NSString*) errorMessage
{
_alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"fout", nil) message:errorMessage delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
_alert.delegate = self;
[_alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)
{
if(self.navigationController != nil)
{
[self.navigationController popViewControllerAnimated:YES];
}
else
{
//[self initializeData];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated
{
[_dm cancelCenterRequest];
/*if(self.tabBarController != nil)
{
dm = [[DataManager alloc]init];
settings = [dm loadSettings];
if([dm hasConnectivity])
{
settings.lastUpdated = nil;
[dm storeSettings:settings];
}
if(settings.loadedCenter.centerCode != settings.chosenCenter.centerCode)
{
UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SplashScreenController *controller = [mystoryboard instantiateViewControllerWithIdentifier:#"root"];
[self presentViewController:controller animated:YES completion:nil];
}
dm = nil;
settings = nil;
}
*/
}
-(void)gaVerder
{
_dm = [[DataManager alloc]init];
GSettings* settings = [_dm loadSettings];
if(settings == nil)
{
settings = [[GSettings alloc]init];
settings.notificationsEnabled = YES;
}
if(_center != nil)
{
settings.chosenCenter = _center;
}
[_dm storeSettings:settings];
[_mapView removeFromSuperview];
_mapView = nil;
_titleBackground = nil;
_lblTitle = nil;
_btnGaVerder = nil;
_myPickerView = nil;
_point = nil;
_indicator = nil;
_alert = nil;
_centers = nil;
_adresLine = nil;
_cityLine = nil;
_center = nil;
_dm = nil;
[self.presentingViewController dismissViewControllerAnimated:NO completion:^{}];
//DEZE BLIJFT HELAAS IN HET GEHEUGEN HANGEN... GEEN OPLOSSING GEVONDEN
//[self.navigationController popViewControllerAnimated:NO];
}
//PICKERVIEWDELEGATE EN DATASOURCE
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [_centers count];
}
- (UILabel *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
GCenter* center = (GCenter*)[_centers objectAtIndex:row];
NSString* string = center.name;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
label.textColor = [GColor blueColor];
label.font = [label.font fontWithSize:18];
label.text = string;
label.textAlignment = NSTextAlignmentCenter;
return label;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_center = (GCenter*)[_centers objectAtIndex:row];
[self changeAddressLines];
}
-(void)changeAddressLines
{
if (_mapView != nil)
{
[_mapView removeAnnotation:_point];
}
[_adresLine removeFromSuperview];
[_cityLine removeFromSuperview];
_adresLine = nil;
_cityLine = nil;
CGRect rctAdres = CGRectMake(0, _myPickerView.frame.origin.y + _myPickerView.frame.size.height -10, self.view.frame.size.width, 20);
_adresLine = [[UILabel alloc]initWithFrame:rctAdres];
_adresLine.textAlignment = NSTextAlignmentCenter;
_adresLine.textColor = [GColor greyColor];
_adresLine.text = _center.street;
CGRect rctCity = CGRectMake(0, rctAdres.origin.y + rctAdres.size.height, self.view.frame.size.width, 20);
_cityLine = [[UILabel alloc]initWithFrame:rctCity];
_cityLine.textAlignment = NSTextAlignmentCenter;
_cityLine.textColor = [GColor greyColor];
_cityLine.font = [_cityLine.font fontWithSize:14];
_cityLine.text = _center.city;
[self.view addSubview:_adresLine];
[self.view addSubview:_cityLine];
if(_mapView == nil)
{
double height;
height = _btnGaVerder.frame.origin.y - _cityLine.frame.origin.y - _cityLine.frame.size.height;
CGRect mapRect = CGRectMake(0, _cityLine.frame.origin.y+3 + _cityLine.frame.size.height, self.view.frame.size.width, height);
_mapView = [[MKMapView alloc]initWithFrame:mapRect];
[self.view addSubview:_mapView];
}
CLLocationCoordinate2D punt;
punt.latitude = _center.latitude;
punt.longitude = _center.longitude;
_point = [[MKPointAnnotation alloc] init];
[_point setCoordinate:punt];
_mapView.centerCoordinate = punt;
_point.title = _center.name;
[_mapView addAnnotation:_point];
[_mapView setCenterCoordinate:punt animated:YES];
MKCoordinateRegion theRegion = _mapView.region;
theRegion.span.longitudeDelta = 0.005;
theRegion.span.latitudeDelta = 0.005;
[_mapView setRegion:theRegion animated:YES];
}
#end
In my case it was a little more complicated. I don't have any variable that has strong reference to my view controller, and my view controller is not a strong delegate to any property/variable contained inside this class itself. After some hard thinking and trials, I found my issue was caused by a NSTimer object defined in the interface. The timer object itself is non-repeatable, but the method invoked by it will schedule the timer again at the end, which as you can imagine would reference this method defined in my view controller again, thus causing circular references. To break out of this loop, I had to invalidate the timer before I dismiss my view controller.
As a summary, these are cases when a view controller can be blocked from deallocating after it is dismissed:
The view controller is being strongly referenced by some outside object;
The view controller is a strong delegate referenced by some object defined within the view controller itself
The dismissViewControllerAnimated:completion: block may reference to self or it has some other code block that may cause a circular references
The view controller has NSTimer objects which can invoke some methods which re-schedules the timer
There could be more, but hopefully we can capture a lot of cases with the above cases.
If your view controller is not deallocated after it is dismissed, there's probably a strong reference to that view controller somewhere in your code. ARC will always deallocate objects that doesn't have strong reference anymore.
There is grey colour in background and I cannot make full size of the PDF. Is there a way to make full screen of the PDF? I have detected the orientation and made the pdf size accordingly.
Edited:
NSString *path = [[NSBundle mainBundle] pathForResource:#"PDF2" ofType:#"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:path];
PDFDocument = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfUrl);
totalPages = (int)CGPDFDocumentGetNumberOfPages(PDFDocument);
//modelArray holds the page numbers
modelArray = [[NSMutableArray alloc] init];
for (int index = 1; index <= totalPages; index++) {
[modelArray addObject:[NSString stringWithFormat:#"%i", index]];
}
thePageViewController = [[UIPageViewController alloc]
initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
options:nil];
thePageViewController.delegate = self;
thePageViewController.dataSource = self;
thePageViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
contentViewController = [[ContentViewController alloc] initWithPDF:PDFDocument];
contentViewController.page = [modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[thePageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:thePageViewController];
[self.view addSubview:thePageViewController.view];
thePageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[thePageViewController didMoveToParentViewController:self];
self.view.backgroundColor = [UIColor underPageBackgroundColor];
I'm using a delegate UITabbarController with transition animation like this:
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
NSArray *tabViewControllers = tabBarController.viewControllers;
UIView * fromView = tabBarController.selectedViewController.view;
UIView * toView = viewController.view;
if (fromView == toView)
return TRUE;
NSUInteger fromIndex = [tabViewControllers indexOfObject:tabBarController.selectedViewController];
NSUInteger toIndex = [tabViewControllers indexOfObject:viewController];
[UIView transitionFromView:fromView
toView:toView
duration:0.3
options: toIndex > fromIndex ? UIViewAnimationOptionTransitionFlipFromLeft : UIViewAnimationOptionTransitionFlipFromRight
completion:^(BOOL finished) {
if (finished) {
tabBarController.selectedIndex = toIndex;
}
}];
return true;
}
Only this broke my entire ViewDidAppear on the views. I'm resetting the UIWebView to the homepage when switching between tabs, but this doesn't work anymore. Any suggestions? Here's my VieDidLoad:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_progressProxy = [[NJKWebViewProgress alloc] init];
_webView.delegate = _progressProxy;
_progressProxy.webViewProxyDelegate = self;
_progressProxy.progressDelegate = self;
[self loadSite];
[TestFlight passCheckpoint:#"Bekijkt homepage"];
}
[self loadSite]; is defined as:
-(void)loadSite
{
NSString *dealerurl = [[NSUserDefaults standardUserDefaults] stringForKey:#"name_preference"];
NSString *urlAddress= #"http://www.sportdirect.com/shop/";
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlAddress]];
[_webView loadRequest:req];
[[_webView scrollView] setBounces: NO];
}
Thanks in advance.
Change:
[_webView loadRequest:req];
to this:
self.webView loadRequest:req;
I think this will undo the nil.