Loading Indicator on Web View - ios

My app shows articles from an RSS feed in a table view then when you select a row, opens a web view controller to show the article. I'm trying to add a loading indicator. If I select a row, the indicator will show briefly and then disappear before the page is fully loaded. Also, if I go back to the table view and select a different row, the loading indicator never shows up. I'm using a custom loading indicator called SVProgressHUD and it works fine elsewhere in the app. I don't think that is the problem though. What am I doing wrong?
Here is my didSelectRowAtIndexPath method in my table view:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"about:blank"]]];
[self.navigationController pushViewController:webViewController animated:YES];
// Grab the selected item
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
// Construct a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];
// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Load the request into the web view
[[webViewController webView]loadRequest:req];
webViewController.hackyURL = url;
}
The loading indicator is started on this line in viewDidLoad of the WebViewController:
[SVProgressHUD showWithStatus:#"Loading"];
And here is my WebViewController.
#import "WebViewController.h"
#import "TUSafariActivity.h"
#import "SVProgressHUD.h"
#implementation WebViewController
#synthesize webView=webView, hackyURL=hackyURL;
- (void)loadView
{
// Create an instance of UIWebView as large as the screen
CGRect screenFrame = [[UIScreen mainScreen]applicationFrame];
UIWebView *wv = [[UIWebView alloc]initWithFrame:screenFrame];
webView = wv;
NSLog(#"%#",webView.request.URL);
// Tell web view to scale web content to fit within bounds of webview
[wv setScalesPageToFit:YES];
[self setView:wv];
}
- (UIWebView *)webView
{
return (UIWebView *)[self view];
}
- (void) showMenu
{
NSURL *urlToShare = hackyURL;
NSArray *activityItems = #[urlToShare];
TUSafariActivity *activity = [[TUSafariActivity alloc] init];
__block UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:#[activity]];
activityVC.excludedActivityTypes = #[UIActivityTypeAssignToContact, UIActivityTypePostToWeibo, UIActivityTypeSaveToCameraRoll];
[self presentViewController:activityVC animated:YES completion:^{activityVC.excludedActivityTypes = nil; activityVC = nil;}];
}
- (void)toggleBars:(UITapGestureRecognizer *)gesture
{
BOOL barsHidden = self.navigationController.navigationBar.hidden;
if (!barsHidden)
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
[self hideTabBar:self.tabBarController];
}
else if (barsHidden)
{
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
[self showTabBar:self.tabBarController];
}
[self.navigationController setNavigationBarHidden:!barsHidden animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[SVProgressHUD showWithStatus:#"Loading"];
UIBarButtonItem *systemAction = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(showMenu)];
self.navigationItem.rightBarButtonItem = systemAction;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(toggleBars:)];
[webView addGestureRecognizer:singleTap];
singleTap.delegate = self;
// self.hidesBottomBarWhenPushed = YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
float fHeight = screenRect.size.height;
if( UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
{
fHeight = screenRect.size.width;
}
for(UIView *view in tabbarcontroller.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
else
{
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
view.backgroundColor = [UIColor blackColor];
}
}
[UIView commitAnimations];
}
- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
float fHeight = screenRect.size.height - 49.0;
if( UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
{
fHeight = screenRect.size.width - 49.0;
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in tabbarcontroller.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
else
{
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
}
}
[UIView commitAnimations];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//stop the activity indicator when done loading
[SVProgressHUD dismiss];
}
#end

You should use the delegate functions of a webview see below
-(void)webViewDidStartLoad:(UIWebView *)webView{
//SHOW HUD
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
//KILL HUD
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
if(!webView.loading){
//KILL HUD
}
}
In webview normally caching happens, so HUD might not show for long as it will show for the first load.
I hope it will help you.

This is fixed. I just had to add
webView.delegate = self;

Related

How to create custom slide menu without third party library.?

I want to implement slide menu in my iOS app like drawer (Andriod). I went through a tutorial, but all of them are using third party libraries. Is there any possibility to create a custom slide menu. I tried to create it with the following code, but it's only working with xib file:
- (IBAction)sidemenu:(id)sender
{
[UIView animateWithDuration:0.50f animations:^{
view.frame = self.view.frame;
} completion:^(BOOL finished) {
swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(SwipGestureLeftAction:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
}];
}
- (void)SwipGestureAction
{
UISwipeGestureRecognizer *swiperight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(SwipGestureRightAction:)];
swiperight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swiperight];
}
#pragma mark AddSwipeGestureLeftAndRight
- (void)SwipGestureRightAction:(UISwipeGestureRecognizer *)swipeRight
{
[UIView animateWithDuration:0.50f animations:^{
view.frame = self.view.frame;
} completion:^(BOOL finished) {
swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(SwipGestureLeftAction:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
}];
}
- (void)SwipGestureLeftAction:(UISwipeGestureRecognizer *)swipeRight
{
[UIView animateWithDuration:0.50f animations:^{
[view setFrame:CGRectMake(self.view.frame.origin.x - self.view.frame.size.width, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
} completion:^(BOOL finished){
[self.view removeGestureRecognizer:swipeLeft];
}];
}
Here is what I have for you:
I made a super class for all my slide menus in all projects. It manages the showing and hiding of the slide menu, and handles orientation changes. It slides in from left on top of the current view, and it partially obscures the remainder of the view with a dark transparent background.
If you ever need other behaviour (like pushing out the current view) just override the animation part.
My slide menu is a Singleton because in our applications we only use one slide menu on every screen.
#import <UIKit/UIKit.h>
#interface IS_SlideMenu_View : UIView <UIGestureRecognizerDelegate>
{
UIView* transparentBgView;
BOOL hidden;
int lastOrientation;
}
#property (strong, nonatomic) UIView *menuContainerV;
+ (id)sharedInstance;
- (BOOL)isShown;
- (void)hideSlideMenu;
- (void)showSlideMenu;
#end
#import "IS_SlideMenu_View.h"
#implementation IS_SlideMenu_View
+ (id)sharedInstance
{
static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[[self class] alloc] init];
});
return _sharedInstance;
}
- (instancetype)initWithFrame:(CGRect)frame
{
frame = [[[UIApplication sharedApplication] delegate] window].frame;
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
transparentBgView = [[UIView alloc] initWithFrame:frame];
[transparentBgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]];
[transparentBgView setAlpha:0];
transparentBgView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureRecognized:)];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(gestureRecognized:)];
[transparentBgView addGestureRecognizer:tap];
[transparentBgView addGestureRecognizer:pan];
[self addSubview:transparentBgView];
frame.size.width = 280;
self.menuContainerV = [[UIView alloc] initWithFrame:frame];
CALayer *l = self.menuContainerV.layer;
l.shadowColor = [UIColor blackColor].CGColor;
l.shadowOffset = CGSizeMake(10, 0);
l.shadowOpacity = 1;
l.masksToBounds = NO;
l.shadowRadius = 10;
self.menuContainerV.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview: self.menuContainerV];
hidden = YES;
}
//----- SETUP DEVICE ORIENTATION CHANGE NOTIFICATION -----
UIDevice *device = [UIDevice currentDevice];
[device beginGeneratingDeviceOrientationNotifications];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:device];
lastOrientation = [[UIDevice currentDevice] orientation];
return self;
}
//********** ORIENTATION CHANGED **********
- (void)orientationChanged:(NSNotification *)note
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if(orientation == UIDeviceOrientationPortrait || orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight){
NSLog(#"%ld",orientation);
if(!hidden && lastOrientation != orientation){
[self hideSlideMenu];
hidden = YES;
lastOrientation = orientation;
}
}
}
- (void)showSlideMenu {
UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
self.frame = CGRectMake(0, 0, window.frame.size.width, window.frame.size.height);
[self.menuContainerV setTransform:CGAffineTransformMakeTranslation(-window.frame.size.width, 0)];
[window addSubview:self];
// [[UIApplication sharedApplication] setStatusBarHidden:YES];
[UIView animateWithDuration:0.5 animations:^{
[self.menuContainerV setTransform:CGAffineTransformIdentity];
[transparentBgView setAlpha:1];
} completion:^(BOOL finished) {
NSLog(#"Show complete!");
hidden = NO;
}];
}
- (void)gestureRecognized:(UIGestureRecognizer *)recognizer
{
if ([recognizer isKindOfClass:[UITapGestureRecognizer class]]) {
[self hideSlideMenu];
} else if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
static CGFloat startX;
if (recognizer.state == UIGestureRecognizerStateBegan) {
startX = [recognizer locationInView:self.window].x;
} else
if (recognizer.state == UIGestureRecognizerStateChanged) {
CGFloat touchLocX = [recognizer locationInView:self.window].x;
if (touchLocX < startX) {
[self.menuContainerV setTransform:CGAffineTransformMakeTranslation(touchLocX - startX, 0)];
}
} else
if (recognizer.state == UIGestureRecognizerStateEnded) {
[self hideSlideMenu];
}
}
}
- (void)hideSlideMenu
{
UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
window.backgroundColor = [UIColor clearColor];
[UIView animateWithDuration:0.5 animations:^{
[self.menuContainerV setTransform:CGAffineTransformMakeTranslation(-self.window.frame.size.width, 0)];
[transparentBgView setAlpha:0];
} completion:^(BOOL finished) {
[self removeFromSuperview];
[self.menuContainerV setTransform:CGAffineTransformIdentity];
// [[UIApplication sharedApplication] setStatusBarHidden:NO];
hidden = YES;
NSLog(#"Hide complete!");
}];
}
- (BOOL)isShown
{
return !hidden;
}
#end
Subclasses only need to add subviews to the menuContainerV view, and manage them.
An example:
I created a subclass that has an header view and a table view as its content. I created the content view in a xib, and the owner of the xib is this subclass. This way I can bind outlets to the xib.
#import "IS_SlideMenu_View.h"
#interface CC_SlideMenu_View : IS_SlideMenu_View<UITableViewDelegate, UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UIView *headerView;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
...
#end
When the slide menu gets instantiated I load the xib and add the content view to the menuContainerV view.
#import "CC_SlideMenu_View.h"
#implementation CC_SlideMenu_View
- (instancetype)init
{
self = [super init];
if (self) {
UIView *v = [[[NSBundle mainBundle] loadNibNamed:#"CC_SlideMenu_View" owner:self options:nil] firstObject];
v.frame = self.menuContainerV.bounds;
[self.menuContainerV addSubview:v];
self.tableView.backgroundColor = [UIColor darkGrayColor];
}
return self;
}
...
#end
The result is something like this.

Objective-c OOP is this the best way to reuse my code from father class?

Im new in OOP and I've read some tutorials and books. I have the concept more or less clear but I haven't seen many examples. I've made a simple webView app which only displays a website and got some tabs and push notifications. It's not the big deal. Almost all the code from father class can be reused, and no need to rewrite it, so I've made some inheritance and overriding solutions to childrens, but I'm would like to know if the way I did it is the correct approach to object oriented way, also with the design and even with the code documentation. I need to show this code in a future job interview and I would like to refine it and also learn about experts from here with with more experience than I have.
Any help would be highly appreciated and many thanks!
This is my father class:
//
// FirstViewController.h
#import <UIKit/UIKit.h>
#import "iAd/iAd.h"
#interface FirstViewController : UIViewController <UIWebViewDelegate,UIGestureRecognizerDelegate, ADBannerViewDelegate, UIScrollViewDelegate>
#property (strong, nonatomic) IBOutlet UITabBarItem *tabInicio;
+(void)viewController:(NSString*)link;
-(void)configureView:(UIViewController*)vista;
-(void)iAdDisplay:(UIViewController*)vista;
-(void)autoResizeWhenRotates:(UIViewController*)vista;
-(void)configureWebView:(UIViewController *)vista withUrlLink:(NSURL *)url;
-(void)showHideStatusBar:(UIViewController*)vista;
-(void)addGestures:(UIViewController*)vista;
-(void)configureToolBar:(UIViewController*)vista;
-(void)addIndicator:(UIViewController*)vista;
#end
And the implementation file:
//
// FirstViewController.m
// push
//
#import "FirstViewController.h"
#interface FirstViewController ()
#property UIActivityIndicatorView *indicator;
#property UIToolbar *cToolBar;
#property BOOL isHidden;
#end
#implementation FirstViewController
static UITabBarController *static_Tab = nil;
static UIWebView* static_iVar = nil;
- (void)viewDidLoad {
[super viewDidLoad];
[self configureView:self];
//configure autoresize when device rotate
NSURL *url = [NSURL URLWithString:#"http://hnoslopez.com"];
[self configureStatic_iVar:self withUrlLink:url];
//Set tab bar icons
[[[self.tabBarController.viewControllers objectAtIndex:1] tabBarItem]setImage:[UIImage imageNamed:#"nosotros.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:2] tabBarItem]setImage:[UIImage imageNamed:#"catalogo.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:3] tabBarItem]setImage:[UIImage imageNamed:#"blog.png"]];
self.tabBarController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.tabBarController.view.autoresizesSubviews = YES;
//Set first tab
_tabInicio = [[UITabBarItem alloc] initWithTitle:#"Inicio" image:[UIImage imageNamed:#"inicioIcon.png"] tag:0];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:0];
self.tabBarItem = _tabInicio;
}
-(void)configureView:(UIViewController *)vista{
//configure toolbar
[self configureToolBar:vista];
//show hide status bar with a gesture recognizer and an animation
[self showHideStatusBar:vista];
//iAd display
[self iAdDisplay:vista];
//auto resizing when device rotates
[self autoResizeWhenRotates:vista];
//Add gestures
[self addGestures:vista];
//Add Indicator
[self addIndicator:vista];
}
-(void)configureToolBar:(UIViewController *)vista{
//Add a toolbar, back and reload button...
UIToolbar *cToolBar = [[UIToolbar alloc] init];
//auto resizing
cToolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingNone;
cToolBar.autoresizesSubviews = YES;
cToolBar.frame = CGRectMake(0, 0, vista.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
//Set toolbar properties..
[cToolBar setBarStyle:UIBarStyleBlack];
[cToolBar setTranslucent:YES ];
[cToolBar setTintColor:[UIColor greenColor]];
//Back Button..
NSString *backArrowString = #"\U000025C0\U0000FE0E AtrĂ¡s"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStyleDone target:nil action:#selector(goBack)];
//Reload button..
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:nil action:#selector(refreshControl)];
[right setTintColor:[UIColor greenColor]];
//Flexible space between buttons..
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:back];
[items addObject:flexibleSpace];
[items addObject:right];
[cToolBar setItems:items animated:NO];
[vista.view addSubview:cToolBar];
}
-(void)showHideStatusBar:(UIViewController *)vista{
//Animation performed to hide/show bar when slide your finger..
if ([vista respondsToSelector:#selector(setNeedsStatusBarAppearanceUpdate)]) {
// iOS 7
[vista performSelector:#selector(setNeedsStatusBarAppearanceUpdate)];
} else {
// iOS 6
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
}
-(void)iAdDisplay:(UIViewController*)vista{
//Display iAd..
[vista setCanDisplayBannerAds:YES];
ADBannerView * adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, 44);
adView.delegate = self;
//resizing
adView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
adView.autoresizesSubviews = YES;
[vista.view addSubview:adView];
}
-(void)autoResizeWhenRotates:(UIViewController*)vista{
vista.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
vista.view.autoresizesSubviews = YES;
}
-(void)addGestures:(UIViewController*)vista{
//SWIPE DOWN
UISwipeGestureRecognizer *gest1 = [[UISwipeGestureRecognizer alloc] initWithTarget:vista action:#selector(hideTabBar:)];
gest1.delegate = self;
[gest1 setDirection:UISwipeGestureRecognizerDirectionDown];
[vista.view addGestureRecognizer:gest1];
//SWIPE UP
UISwipeGestureRecognizer *gest2 = [[UISwipeGestureRecognizer alloc] initWithTarget:vista action:#selector(showTabBar:)];
gest2.delegate = self;
[gest2 setDirection:UISwipeGestureRecognizerDirectionUp];
[vista.view addGestureRecognizer:gest2];
}
-(void)addIndicator:(UIViewController *)vista{
//loading indicator
// _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
UIActivityIndicatorView* indicador = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicador setCenter:vista.view.center];
[indicador setHidesWhenStopped:YES];
//resizing
indicador.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
indicador.autoresizesSubviews = YES;
[vista.view addSubview:indicador];
[indicador startAnimating];
}
-(void)configureWebView:(UIViewController *)vista withUrlLink:(NSURL *)url{
//Children method to configure children webViews...
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
webView.delegate = self;
//ADD Delegate to disable lateral scroll
webView.scrollView.delegate = self;
//auto resizing
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
webView.autoresizesSubviews = YES;
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[vista.view addSubview:webView];
}
-(void)configureStatic_iVar:(UIViewController *)vista withUrlLink:(NSURL *)url{
//Configure father class webView...
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
static_iVar = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
static_iVar.delegate = self;
//ADD Delegate to disable lateral scroll
static_iVar.scrollView.delegate = self;
//auto resizing
static_iVar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
static_iVar.autoresizesSubviews = YES;
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar loadRequest:requestObj];
[vista.view addSubview:static_iVar];
}
#pragma - mark selectors
-(void)goBack{
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews){
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(goBack)])
{
[subview performSelector:#selector(goBack)];
}
}
}
-(void)refreshControl{
[super viewDidAppear:YES];
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(reload)])
{
[subview performSelector:#selector(reload)];
}
}
}
- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
//Perform animation to hide tab bar
CGRect screenRect = [[UIScreen mainScreen] bounds];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
float fHeight = screenRect.size.height;
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
//Perform animation to show tab bar..
CGRect screenRect = [[UIScreen mainScreen] bounds];
float fHeight = screenRect.size.height - self.tabBarController.tabBar.frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]] )
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
+(void)viewController:(NSString*)link{
//Loads push notification links in first tab..
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar loadRequest:requestObj];
}
#pragma mark - delegate methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
CGSize contentSize = webView.scrollView.contentSize;
CGSize viewSize = self.view.bounds.size;
float rw = viewSize.width / contentSize.width;
webView.scrollView.minimumZoomScale = rw;
webView.scrollView.maximumZoomScale = rw;
webView.scrollView.zoomScale = rw;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return TRUE;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
return YES;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
[scrollView setContentOffset:CGPointMake(0, scrollView.contentOffset.y)];
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And this is a children viewController:
//
// SecondViewController.h
//
#import <UIKit/UIKit.h>
#import "iAd/iAd.h"
#import "FirstViewController.h"
#interface secondViewController : FirstViewController <UIWebViewDelegate,UIGestureRecognizerDelegate,ADBannerViewDelegate, UIScrollViewDelegate>
#property (weak, nonatomic) IBOutlet UIWebView *secondView;
#property (strong, nonatomic) IBOutlet UITabBarItem *secondTab;
#end
Implementation file:
//
// SecondViewController.m
//
//
#import "secondViewController.h"
#import "iAd/iAd.h"
#interface secondViewController ()
#property UIActivityIndicatorView *indicador;
#end
#implementation secondViewController
- (void)viewDidLoad {
[super viewDidLoad];
[super configureView:self];
//configure webView
NSURL *url = [NSURL URLWithString:#"http://hnoslopez.com/nosotros/"];
[self configureWebView:self withUrlLink:url];
//Configure second tab
_secondTab = [[UITabBarItem alloc] initWithTitle:#"Nosotros" image:[UIImage imageNamed:#"nosotros.png"] tag:1];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:1];
self.tabBarItem = _secondTab;
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
-(void)goBack{
//reloads webView
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews){
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(goBack)])
{
[subview performSelector:#selector(goBack)];
}
}
}
-(void)refreshControl{
[super viewDidAppear:YES];
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
//start animating indicator
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
//reloads webView
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(reload)])
{
[subview performSelector:#selector(reload)];
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
CGSize contentSize = webView.scrollView.contentSize;
CGSize viewSize = self.view.bounds.size;
float rw = viewSize.width / contentSize.width;
webView.scrollView.minimumZoomScale = rw;
webView.scrollView.maximumZoomScale = rw;
webView.scrollView.zoomScale = rw;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return TRUE;
}
- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
float fHeight = screenRect.size.height;
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
float fHeight = screenRect.size.height - self.tabBarController.tabBar.frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]] )
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
return YES;
}
#pragma mark resuelve problema de que la pagina hace scroll horizontal
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
[scrollView setContentOffset:CGPointMake(0, scrollView.contentOffset.y)];
}
#end

Sliding Between UISegmentedControl Views

Currently I am wanting to create a slide animation when the user selects on a segmented button of a UISegmentedControl instantiated on top of a navigationbar. Currently I have a UISegmentedControl with 6 buttons the user is allowed to press and select to go to different views.
Everything works accordingly but I am having an issue with implementing the slide transition, if it is even possible.
I am able to implement a slide transition between UITabBar views using this method:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
int controllerIndex = [[tabBarController viewControllers] indexOfObject:viewController];
if(controllerIndex == self.selectedIndex || self.isAnimating){
return NO;
}
// Get the views.
UIView * fromView = tabBarController.selectedViewController.view;
UIView * toView = [viewController view];
// Get the size of the view area.
CGRect viewSize = fromView.frame;
BOOL scrollRight = controllerIndex > tabBarController.selectedIndex;
// Add the to view to the tab bar view.
[fromView.superview addSubview:toView];
// Position it off screen.
toView.frame = CGRectMake((scrollRight ? 320 : -320), viewSize.origin.y, 320, viewSize.size.height);
[UIView animateWithDuration:0.2 animations: ^{
// Animate the views on and off the screen. This will appear to slide.
fromView.frame =CGRectMake((scrollRight ? -320 : 320), viewSize.origin.y, 320, viewSize.size.height);
toView.frame =CGRectMake(0, viewSize.origin.y, 320, viewSize.size.height);
} completion:^(BOOL finished) {
if (finished) {
// Remove the old view from the tabbar view.
[fromView removeFromSuperview];
tabBarController.selectedIndex = controllerIndex;
}
}
];
return NO;
}
Not so sure if the same rules apply for a UISegmentedControl of several viewcontrollers. Is this possible to do? I figure it should be but anyone have any ideas on how to get started?
EDIT
Heres the code I use within my segmentedcontroller...
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
/* This bunch of code creates the segmentedControllerButtons in the nav bar */
self.segmentedViewControllers = [self segmentedViewControllerContent];
NSArray * segmentTitles = #[#"Plant", #"Net", #"Wiz", #"Date", #"Clone", #"GF/E"];
self.segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentTitles];
self.segmentedControl.selectedSegmentIndex = 0;
self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[self.segmentedControl addTarget:self action:#selector(didChangeSegmentControl:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = self.segmentedControl;
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
self.segmentedControl.tintColor = [UIColor redColor];
[self didChangeSegmentControl:self.segmentedControl]; // kick everything off
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSArray *)segmentedViewControllerContent {
CDDConfigPlantViewController *plant = [[CDDConfigPlantViewController alloc] initWithNibName:#"CDDConfigPlantViewController" bundle:nil];
plant->ipAddress = ipAddress;
plant->encode = encodedInfo;
CDDConfigNetworkViewController *network = [[CDDConfigNetworkViewController alloc] initWithNibName:#"CDDConfigNetworkViewController" bundle:nil];
network->ipAddress = ipAddress;
network->encode = encodedInfo;
CDDConfigAcquisitionWizardViewController *acquisition_wizard = [[CDDConfigAcquisitionWizardViewController alloc] initWithNibName:#"CDDConfigAcquisitionWizardViewController" bundle:nil];
acquisition_wizard->ipAddress = ipAddress;
acquisition_wizard->encode = encodedInfo;
CDDConfigDateTimeViewController *date_time = [[CDDConfigDateTimeViewController alloc] initWithNibName:#"CDDConfigDateTimeViewController" bundle:nil];
date_time->ipAddress = ipAddress;
date_time->encode = encodedInfo;
CDDConfigCDDCloneViewController *cdd_clone = [[CDDConfigCDDCloneViewController alloc] initWithNibName:#"CDDConfigCDDCloneViewController" bundle:nil];
cdd_clone->ipAddress = ipAddress;
cdd_clone->encode = encodedInfo;
CDDConfigGroundfaultEnergyViewController *groundfault_energy = [[CDDConfigGroundfaultEnergyViewController alloc] initWithNibName:#"CDDConfigGroundfaultEnergyViewController" bundle:nil];
groundfault_energy->ipAddress = ipAddress;
groundfault_energy->encode = encodedInfo;
NSArray * controllers = [NSArray arrayWithObjects:plant, network, acquisition_wizard, date_time, cdd_clone, groundfault_energy, nil];
return controllers;
}
#pragma mark -
#pragma mark Segment control
- (void)didChangeSegmentControl:(UISegmentedControl *)control {
if (self.activeViewController) {
[self.activeViewController viewWillDisappear:NO];
[self.activeViewController.view removeFromSuperview];
[self.activeViewController viewDidDisappear:NO];
}
self.activeViewController = [self.segmentedViewControllers objectAtIndex:control.selectedSegmentIndex];
[self.activeViewController viewWillAppear:YES];
[self.view addSubview:self.activeViewController.view];
[self.activeViewController viewDidAppear:YES];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.activeViewController viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.activeViewController viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.activeViewController viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[self.activeViewController viewDidDisappear:animated];
}
Is it UIView you want to animate or UIViewControllers.
If UIView the animateWithDuration: animations: completion: works
if UIViewControllers presentViewController: animated: completion: is the way to go

UIView (subclass) trying to present UIImagePickerController

I have a parent view that allows you to see post in a UITableView. In its Navigation Bar I have a post button that when pressed presents a UIView subclass and shows it on the top of the screen. I have an image on that UIView that when tapped I want to present the UIImagePickerController to allow users to pick an image to post to the service. How can I do this since my subview is not a view controller it cannot present the UIImagePickerController.
Below is my subview code.
#import "PostView.h"
#implementation PostView
#synthesize attachedLabel;
#synthesize postButton;
#synthesize textView;
#synthesize characterLimit;
#synthesize attachImage;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
NSArray *xib = [[NSBundle mainBundle] loadNibNamed:#"PostView" owner:self options:nil];
PostView *view = [xib objectAtIndex:0];
[view setBackgroundColor:[UIColor whiteColor]];
[view setAlpha:0.7f];
attachedLabel = [[UILabel alloc] initWithFrame:CGRectMake(204, 212, 56, 21)];
attachedLabel.textColor = [UIColor blackColor];
[attachedLabel setText:#"Attached"];
attachedLabel.backgroundColor = [UIColor clearColor];
attachedLabel.font = [UIFont fontWithName:text_font_name size:12.0];
characterLimit = [[UILabel alloc] initWithFrame:CGRectMake(246, 13, 50, 21)];
[characterLimit setTextAlignment:NSTextAlignmentRight];
characterLimit.textColor = [UIColor blackColor];
characterLimit.backgroundColor = [UIColor clearColor];
characterLimit.font = [UIFont fontWithName:text_font_name size:12.0];
attachImage = [[UIImageView alloc] initWithFrame:CGRectMake(270, 208, 30, 30)];
[attachImage setImage:[UIImage imageNamed:#"attachphoto30x30.png"]];
[self.textView setDelegate:self];
[self.textView setAlpha:0.7f];
[self.textView setTextColor:[UIColor whiteColor]];
[self.textView setBackgroundColor:[UIColor clearColor]];
self.layer.cornerRadius = 10.0f;
self.layer.masksToBounds = YES;
[self addSubview:view];
[self addSubview:characterLimit];
[self addSubview:attachedLabel];
[self addSubview:attachImage];
}
return self;
}
- (IBAction)openCamera:(id)sender
{
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
//[self presentViewController:controller animated:YES completion:nil];
NSLog(#"%#", #"Image Tapped");
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
/*[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage];
UIImage *scale = [image scaleToSize:CGSizeMake(320.0f, 548.0f)];
imageData = UIImageJPEGRepresentation(scale, 1);
encodedImage = [self Base64Encode:imageData];
[attachedLabel setHidden:NO];
*/
}
#pragma mark Custom alert methods
- (IBAction)postAction:(id)sender
{
[self hide];
}
- (void)show
{
//prepare attachImage
attachImage.userInteractionEnabled = YES;
UITapGestureRecognizer *tapAttach = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(openCamera:)];
tapAttach.numberOfTapsRequired = 1;
[self.attachImage addGestureRecognizer:tapAttach];
isShown = YES;
self.transform = CGAffineTransformMakeScale(0.1, 0.1);
self.alpha = 0;
[UIView beginAnimations:#"showAlert" context:nil];
[self setBackgroundColor:[UIColor clearColor]];
[UIView setAnimationDelegate:self];
self.transform = CGAffineTransformMakeScale(1.1, 1.1);
self.alpha = 1;
[UIView commitAnimations];
}
- (void)hide
{
isShown = NO;
[UIView beginAnimations:#"hideAlert" context:nil];
[UIView setAnimationDelegate:self];
[[NSNotificationCenter defaultCenter] postNotificationName:#"hidePostView_Notification" object:nil];
self.transform = CGAffineTransformMakeScale(0.1, 0.1);
self.alpha = 0;
[UIView commitAnimations];
}
- (void)toggle
{
if (isShown)
{
[self hide];
} else
{
[self show];
}
}
#pragma mark Animation delegate
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if ([animationID isEqualToString:#"showAlert"])
{
if (finished)
{
[UIView beginAnimations:nil context:nil];
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
[UIView commitAnimations];
}
} else if ([animationID isEqualToString:#"hideAlert"])
{
if (finished)
{
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
self.frame = originalFrame;
}
}
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
return YES;
}
- (BOOL)textView:(UITextView *)textViewer shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string
{
if ([string isEqualToString:#"\n"])
{
[textViewer resignFirstResponder];
}
return [self isAcceptableTextLength:textViewer.text.length + string.length - range.length];
}
-(IBAction)checkIfCorrectLength:(id)sender
{
if (![self isAcceptableTextLength:self.textView.text.length])
{
// do something to make text shorter
}
}
- (BOOL)isAcceptableTextLength:(NSUInteger)length
{
return length <= 160;
}
- (void)textViewDidChange:(UITextView *)textViewer
{
NSString *characters = [[NSString stringWithFormat:#"%d", textViewer.text.length] stringByAppendingString:#"/160"];
NSLog(#"%#", characters);
[self updateDisplay:characters];
}
-(void) updateDisplay : (NSString *)str
{
[self.characterLimit performSelectorOnMainThread : # selector(setText : ) withObject:str waitUntilDone:YES];
}
#end
Yes, you can not present a viewcontroller from a UIView subclass.
To solve this problem, you can use your subview's superview's viewcontroller class. calling [self.superview nextResponder] in your subview will return you the superview's viewcontroller. Using that you can present your UIImagePicker view controller. To use the presentViewController method, you should cast [self.superview nextResponder] to your parentviewcontroller's class type. Also make sure you import parentview controller.h inside subview.m file
[(YourParentViewController *)[self.superview nextResponder] presentViewController:controller animated:YES completion:nil];
You should present a UIViewController subclass rather than a UIView subclass.
I would also say that UIViewController should be responsible for handling data and operational logic for its views. Check out some of the docs:
View Controller Basics:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/AboutViewControllers/AboutViewControllers.html
UIViewController Class Reference:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/AboutViewControllers/AboutViewControllers.html

Restrict my project to portrait only leaving photo view's in landscape/portrait

I want my whole project to run in portrait mode only and only the view that's for viewing the photo's can turn on landscape same as if using the facebook (we view photo's they turn landscape also but other view's remains in portrait) i want to know that how it's done as i have a table view that has images that i get from the DB from the server and every particular data contains different number's of photo's so now i want that after the user select's the photo's they should open up fully and can be viewed in landscape and in portrait as well i did tried
I am working with ios6
- (BOOL)shouldAutorotate
{
return NO;
}
implementing in all the view's so that they can remain in portrait but still they turn in landscape how should i restrict it and please can any one tell me that in one of my class i have images in table view(loaded from the DB) and i have another class that open's up the selected photo from the table
My PhotoView.m class
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dic = [photos objectAtIndex:indexPath.row];
NSLog(#" *** url is %#",[dic objectForKey:#"url"]);
[self.delegate showPhotoAtUrl:[dic objectForKey:#"url"]];
}
My PhotoViewController.h class
#import <UIKit/UIKit.h>
#interface PhotoViewController : UIViewController <UIScrollViewDelegate>
{
NSString *url;
UIButton *doneButton;
}
#property (nonatomic, retain) UIImageView *imageView;
- (id) initWithPhotoUrl:(NSString *)photoUrl;
#end
and PhotoViewController.m class
#import "PhotoViewController.h"
#interface PhotoViewController ()
#end
#implementation PhotoViewController
#synthesize imageView;
- (id) initWithPhotoUrl:(NSString *)photoUrl
{
self = [super init];
if(self) {
url = [photoUrl retain];
}
return self;
}
- (void)dealloc
{
[url release];
self.imageView = nil;
[doneButton release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.tag = 1;
spinner.center = self.view.center;
[spinner startAnimating];
[self.view addSubview:spinner];
[spinner release];
[self performSelectorInBackground:#selector(loadPhotoData) withObject:nil];
doneButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[doneButton addTarget:self action:#selector(doneTouched) forControlEvents:UIControlEventTouchUpInside];
[doneButton setTitle:#"done" forState:UIControlStateNormal];
[doneButton setBackgroundColor:[UIColor clearColor]];
doneButton.frame = CGRectMake(2, 2, 60, 30);
[self.view addSubview:doneButton];
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.title = #"";
self.navigationController.navigationBarHidden = YES;
}
- (void) doneTouched
{
[self.navigationController popViewControllerAnimated:YES];
}
- (void) loadComplete:(NSData *)imageData
{
if(!imageData) return;
UIActivityIndicatorView *spinner = (UIActivityIndicatorView *)[self.view viewWithTag:1];
if(spinner) {
[spinner stopAnimating];
[spinner removeFromSuperview];
}
UIImage *img = [UIImage imageWithData:imageData];
float scale = MIN(self.view.frame.size.width/img.size.width, self.view.frame.size.height/img.size.height);
self.imageView = [[[UIImageView alloc] initWithImage:img] autorelease];
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width*scale, self.imageView.image.size.height*scale);
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
self.imageView.center = scrollView.center;
scrollView.delegate = self;
scrollView.contentSize = self.imageView.frame.size;
scrollView.minimumZoomScale = 1;
scrollView.maximumZoomScale = 2;
[scrollView addSubview:self.imageView];
[self.view addSubview:scrollView];
[scrollView release];
[self.view bringSubviewToFront:doneButton];
}
- (UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
- (void) loadPhotoData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[self performSelectorOnMainThread:#selector(loadComplete:) withObject:imageData waitUntilDone:NO];
[pool drain];
}
#end
and in the main class i have have this method that calls the PhotoViewController to load the selected photo
- (void) showPhotoAtUrl:(NSString *)url
{
PhotoViewController *vc = [[PhotoViewController alloc] initWithPhotoUrl:url];
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}
Now my problem is how should i get the images after getting selected from the table to be open up in the same type of the view that open's up in FB app (open's the selected photo in portrait/landscape compatible view) i am only able to get one photo in my PhotoViewController class can any one tell me how can i add all the photo's to the PhotoViewController class so that i get the effect that i want ?... Any code help will be very helpful .. Thanks in Advance for contributing your time
In Short i have two things to do :
I have to restrict my project to only portrait mode leaving only the photo's view to have landscape/portrait compatibility.
I am currently having the photo's in my table view that i want on selection to open up in the same style(landscape/portrait compatibile) as FB or other app's do while viewing the photo's.
These only work on iOS 6.0
-(BOOL)shouldAutorotate
{
return YES;
}
-(NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationLandscapeRight | UIInterfaceOrientationLandscapeLeft);
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscapeRight;
}
The method will return which orientation mode to use first.
Below are supportedInterfaceOrientations:
UIInterfaceOrientationMaskPortrait
UIInterfaceOrientationMaskLandscapeLeft
UIInterfaceOrientationMaskLandscapeRight
UIInterfaceOrientationMaskPortraitUpsideDown
UIInterfaceOrientationMaskLandscape
UIInterfaceOrientationMaskAll
UIInterfaceOrientationMaskAllButUpsideDown
For iOS > 4.0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
Other ViewControllers will have
-(BOOL)shouldAutorotate { return NO; }
-(BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation{
return NO;
}

Resources