ViewDidAppear is not being called - ios

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.

Related

UIPageViewController does not show its view controllers views

I have a UIPageViewController in a UIViewController , I am having a problem where the pageviewcontroller's inner view are not shown [Although I am sure they are loaded from the server]!
Some helpful notes:
UIPageViewController (called :pageController)
Outer UIViewController (called :OfferDetailsViewController)
each viewController inside the pageController is of type OfferBannerPageViewController
Here is my code related to the problem , Please ask for any other blocks of code if you think it will help finding the problem source
some of :OfferDetailsViewController.m :
- (void)viewDidLoad {
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
if(_offerId)
{
_offer = [[Offer alloc]init];
[delegate setUpAConnectionToGetADetailedOffer:_offerId];
//first: load the offer
[self loadOffer];
[self startTimer];
}
}
-(void) loadOffer{
NSMutableString * pathPattern = [NSMutableString stringWithString: #"api/Offers/"];
[pathPattern appendString:_offerId];
[[RKObjectManager sharedManager]getObjectsAtPath:pathPattern parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if(mappingResult){
_offer = (Offer *)[mappingResult.array firstObject];
//second load the offer banners images
[self setOfferView];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadOfferBanners];
});
}else{
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
}
-(void)loadOfferBanners {
_offer.OfferPannerImagesObjects = [[NSMutableArray alloc]init];
for(int index = 0 ; index<_offer.OfferPannerImages.count ;index++){
NSURL *imageURL =[NSURL URLWithString:_offer.OfferPannerImages[index]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
//[UIImage imageWithData:imageData];
if(image){
[_offer.OfferPannerImagesObjects addObject: image];
}
}
if(_offer.OfferPannerImagesObjects.count>0){
[self setUpOfferBanners];
}
}
-(void)setUpOfferBanners {
self.pageController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageController.dataSource = self;
CGRect rect = [self.pagesView bounds];
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
OfferBannerPageViewController * initialBanner = [self viewControllerAtIndex: 0];
[self.pageController setViewControllers:[NSArray arrayWithObjects:initialBanner, nil] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil ];
[self addChildViewController:self.pageController];
[[self pagesView] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
self.pagesView.clipsToBounds=YES;
self.pagesView.layer.cornerRadius= 6;
}
here is the ViewControllerAtIndex method I debug it and found that index is always whereas when I hover in it after stopping at a break point I see its value as 0!
- (OfferBannerPageViewController *)viewControllerAtIndex:(NSUInteger)index {
OfferBannerPageViewController *offerBannerPageViewController = [[OfferBannerPageViewController alloc] initWithNibName:#"OfferBannerPageViewController" bundle:nil];
offerBannerPageViewController.bannerView = _offer.OfferPannerImagesObjects[index];
offerBannerPageViewController.index = [NSNumber numberWithLong:(long)index];
NSLog(#"____________________ [INDEX = %ld] ___________________",(long)index);
[offerBannerPageViewController.bannerView setImage:_offer.OfferPannerImagesObjects[index]];
return offerBannerPageViewController;
}
any help will be extremely appreciated, Thank you.
update
- (NSInteger)presentationCountForPageViewController: (UIPageViewController*)pageViewController {
// The number of items reflected in the page indicator.
return [_offer.OfferPannerImages count];
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
// The selected item reflected in the page indicator.
return 0;
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index >= _offer.OfferPannerImagesObjects.count){
return nil;
}
index ++;
return [self viewControllerAtIndex:index];
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index == 0)
return nil;
index--;
return [self viewControllerAtIndex:index];
}
update 2: OfferBannerPageViewController.h
#interface OfferBannerPageViewController : UIViewController
#property (strong,nonatomic) NSNumber * index;
#property (strong,nonatomic)IBOutlet UIImageView * bannerView;
#end
Not sure about this, but maybe you should use autoresizing masks to make sure OfferBannerPageViewController's view resizes width and height along with the superview. It might happen that when you set the frame of pageController.view based on bounds of superview, the bounds are 0 width and height and then doesn't resize.
So try:
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
[[self.pageController view] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Have you implemented presentationCountForPageViewController, presentationIndexForPageViewController, viewControllerBeforeViewController and viewControllerAfterViewController methods?
Please, show them.

dismissViewControllerAnimated does not deallocate 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.

Fade Effect when Scrolling

I would like to add the fade effect when user scroll my galleryViewController which fetch the data from the server. I could not able to implement the fade effect to my scrollViewController.
Code:
#import "GrillGalleryCollectionViewController.h"
#import "AFNetworking.h"
#interface GrillGalleryCollectionViewController ()
#end
#implementation GrillGalleryCollectionViewController
#synthesize scrollView,pageControl, colors;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// colors=[[NSArray alloc]init];
colors = [[NSArray alloc] init];;
[self getActiveOffers];
// NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
- (IBAction)backBtnPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void) getActiveOffers {
NSString *string = #"http://znadesign.com/appcenter/api.php?function=get_gallery&customer_id=1";
NSLog(#"%#", string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:#"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:#"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
colors = [NSArray arrayWithArray:array];
[self setSizeSliding];
// [myTableView reloadData];
}
else
{
UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView2 show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
-(void) setSizeSliding
{
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
// UIView *subview = [[UIView alloc] initWithFrame:frame];
// subview.backgroundColor = [colors objectAtIndex:i];
// NSString *imageURLString=[[offersArray objectAtIndex:indexPath.row] valueForKey:#"picture"];
NSString*slidingImage = [[colors objectAtIndex:i] valueForKey:#"picture"];
NSURL *url = [NSURL URLWithString:slidingImage];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
UIImageView *slidingImageView = [[UIImageView alloc]initWithFrame:frame];
slidingImageView.image = tmpImage;
[self.scrollView addSubview:slidingImageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
I want to implement the similar fade effect as it is listed below:
[UIView animateWithDuration:2
animations:^{imageView.alpha = 0.0;}
completion:^(BOOL finished){ [imageView removeFromSuperview];}];
You have the code Can you adding the below code and try whether the animation works..
-(void) animateSubViews
{
int buffer = 10;
CGRect frame = CGRectMake((self.pageControl.currentPage * self.scrollView.frame.size.width)-buffer, 0, self.scrollView.frame.size.width + buffer, self.scrollView.frame.size.height);
[UIView animateWithDuration:0.4
animations:^{
for (UIView *view in self.scrollView.subviews)
{
if (CGRectContainsRect(frame, view.frame))
{
[view setAlpha:1.0];
}
else
{
[view setAlpha:0.0];
}
}
}];
}
Try calling this method from ScrollView did scroll and change page.
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
//Call to animate
[self animateSubViews];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
//Call to animate
[self animateSubViews];
}

Trouble hiding iAd banner and displaying UIWebView in its place

When there is no iAd banner to display, we would like to display a UIWebView of the same dimensions pointed to a specific URL.
However, hiding the iAd banner and showing the UIWebView doesn't work. We embed the show/hide code inside bannerViewDidLoadAd and didFailToReceiveAdWithError. All that appears is the white, blank rectangle when there is no iAd inventory instead of our UIWebView.
If a user clicks on a link inside the UIWebView, we would like the link to open in Safari. Do we need to add a delegate to the UIWebView?
Code:
//
// SAiOSAdPlugin.m
// Ad Plugin for PhoneGap
//
// Created by shazron on 10-07-12.
// Copyright 2010 Shazron Abdullah. All rights reserved.
// Cordova v1.5.0 Support added 2012 #RandyMcMillan
//
#import "SAiOSAdPlugin.h"
//#ifdef CORDOVA_FRAMEWORK
#import <Cordova/CDVDebug.h>
//#else
//#import "CDVDebug.h"
//#endif
#interface SAiOSAdPlugin(PrivateMethods)
- (void) __prepare:(BOOL)atBottom;
- (void) __showAd:(BOOL)show;
#end
#implementation SAiOSAdPlugin
#synthesize adView;
#synthesize bannerIsVisible, bannerIsInitialized, bannerIsAtBottom, isLandscape;
#pragma mark -
#pragma mark Public Methods
- (void) resizeViews
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
CGRect webViewFrame = [super webView].frame;
CGRect superViewFrame = [[super webView] superview].frame;
CGRect adViewFrame = self.adView.frame;
BOOL adIsShowing = [[[super webView] superview].subviews containsObject:self.adView];
if (adIsShowing)
{
if (self.bannerIsAtBottom) {
webViewFrame.origin.y = 0;
CGRect adViewFrame = self.adView.frame;
CGRect superViewFrame = [[super webView] superview].frame;
adViewFrame.origin.y = (self.isLandscape ? superViewFrame.size.width : superViewFrame.size.height) - adViewFrame.size.height;
self.adView.frame = adViewFrame;
} else {
webViewFrame.origin.y = adViewFrame.size.height;
}
webViewFrame.size.height = self.isLandscape? (superViewFrame.size.width - adViewFrame.size.height) : (superViewFrame.size.height - adViewFrame.size.height);
}
else
{
webViewFrame.size = self.isLandscape? CGSizeMake(superViewFrame.size.height, superViewFrame.size.width) : superViewFrame.size;
webViewFrame.origin = CGPointZero;
}
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[super webView].frame = webViewFrame;
[UIView commitAnimations];
}
}
- (void) orientationChanged:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
{
NSInteger orientation = [[arguments objectAtIndex:0] integerValue];
switch (orientation) {
// landscape
case 90:
case -90:
self.isLandscape = YES;
break;
// portrait
case 0:
case 180:
self.isLandscape = NO;
break;
default:
break;
}
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
self.adView.currentContentSizeIdentifier = self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait;
[self resizeViews];
}
}
- (void) prepare:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* atBottomValue = [arguments objectAtIndex:0];
[self __prepare:[atBottomValue boolValue]];
}
- (void) showAd:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* showValue = [arguments objectAtIndex:0];
[self __showAd:[showValue boolValue]];
}
#pragma mark -
#pragma mark Private Methods
- (void) __prepare:(BOOL)atBottom
{
NSLog(#"SAiOSAdPlugin Prepare Ad At Bottom: %d", atBottom);
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && !self.adView)
{
self.adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
// we are still using these constants even though they are deprecated - if it is changed, iOS 4 devices < 4.3 will crash.
// will need to do a run-time iOS version check
self.adView.requiredContentSizeIdentifiers = [NSSet setWithObjects: ADBannerContentSizeIdentifierPortrait, ADBannerContentSizeIdentifierLandscape, nil];
self.adView.delegate = self;
NSString* contentSizeId = (self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait);
self.adView.currentContentSizeIdentifier = contentSizeId;
if (atBottom) {
self.bannerIsAtBottom = YES;
}
self.bannerIsVisible = NO;
self.bannerIsInitialized = YES;
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
}
}
- (void) __showAd:(BOOL)show
{
NSLog(#"SAiOSAdPlugin Show Ad: %d", show);
if (!self.bannerIsInitialized){
[self __prepare:NO];
}
if (!(NSClassFromString(#"ADBannerView") && self.adView)) { // ad classes not available
return;
}
if (show == self.bannerIsVisible) { // same state, nothing to do
return;
}
if (show)
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[[[super webView] superview] addSubview:self.adView];
[[[super webView] superview] bringSubviewToFront:self.houseAdView];
[[[super webView] superview] bringSubviewToFront:self.adView];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = YES;
}
else
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[self.adView removeFromSuperview];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = NO;
}
}
#pragma mark -
#pragma ADBannerViewDelegate
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidLoadAdEvent');"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString]];
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError*)error
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidFailToReceiveAdWithErrorEvent');"
"e.error = '%#';"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString, [error description]]];
}
}
#end
It's me again :)
You're not adding it to the sub view tree.
From your __prepare method
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
That's great. But it doesn't work - you are missing one line of code - a critical, vital line that gets every developer some time or another.
[self addSubview:self.houseAdView];
I'm making a few assumptions, like that self is a UIView. Test before shipping.
So, that part of your __prepare method should look like this:
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
[self addSubview:self.houseAdView];

UITableViewController with UIPageViewController in UIViewController

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.

Resources