Activity Indicator doesn't disappear when webView finishes loading - ios

I am developing iOS App with Objective-c. Then, I am implementing customized Activity Indicator which is active while webView is loading.
The customized Activity Indicator appears when webView starts loading, however it does not disappear when webView finishes loading.
My code is following.
Could you tell me how to solve this problem?
#interface DetailViewController ()<UIWebViewDelegate>{
{
UILabel *loadingLabel;
UIActivityIndicatorView *loadingMark;
UIView *loadingContainer;
}
#property (weak, nonatomic) IBOutlet UIWebView *detailPage;
#end
#implementation DetailViewController
- (void)configureView
{
NSURL *page_url = [NSURL URLWithString:#"http://yahoo.co.jp"];
NSURLRequest *request = [NSURLRequest requestWithURL:page_url];
[_detailPage loadRequest:request];
_detailPage.delegate = self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)webViewDidStartLoad:(UIWebView*)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self animatingIndicator];
}
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
[self stopAndRemoveIndicator];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(void)animatingIndicator {
loadingContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 60)];
//Set Style Of Label
loadingLabel = [[UILabel alloc] init];
loadingLabel.text = #"Loading";
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.shadowColor = [UIColor blackColor];
loadingLabel.shadowOffset = CGSizeMake(1, 1);
loadingLabel.font = [UIFont boldSystemFontOfSize:17];
loadingLabel.backgroundColor = [UIColor lightGrayColor];
loadingLabel.frame = CGRectMake(20, 17, 70, 25);
[loadingContainer addSubview:loadingLabel];
//Set Style Of Mark
loadingMark = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
loadingMark.frame = CGRectMake(100, 14, 30, 30);
[loadingContainer addSubview:loadingMark];
//Set Style Of Container
loadingContainer.backgroundColor = [UIColor lightGrayColor];
[[loadingContainer layer] setCornerRadius:8.0f];
[[loadingContainer layer] setMasksToBounds:YES];
[[loadingContainer layer] setBorderWidth:0.5f];
[[loadingContainer layer] setBorderColor:[[UIColor darkGrayColor] CGColor]];
CGRect rect = self.view.frame;
loadingContainer.center = CGPointMake(rect.size.width/2, rect.size.height/2 * 0.8);
[self.view addSubview:loadingContainer];
[loadingMark startAnimating];
loadingContainer.hidden = NO;
}
-(void)stopAndRemoveIndicator {
[loadingMark stopAnimating];
loadingContainer.hidden = YES;
[loadingMark setHidden:YES];
}

You need to hide the UIKit objects in the main thread.
override func webViewDidFinishLoad(webView:UIWebView)
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.loadingSign.stopAnimating()
self.loadingSign.hidden = true
}
}
Update for swift 4
override func webViewDidFinishLoad(_ webView: UIWebView)
{
DispatchQueue.main.async {
self.loadingSign.stopAnimating()
self.loadingSign.hidden = true
}
}

loadingSign is UIActivity Indicator.
This is what I have done, work fine!
.h file
#property (retain, nonatomic) IBOutlet UIActivityIndicatorView *loadingSign;
.m file
-(void)webViewDidStartLoad:(UIWebView *)webView
{
[self.loadingSign startAnimating];
self.loadingSign.hidden = NO;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[self.loadingSign stopAnimating];
self.loadingSign.hidden = YES;
}

Related

Make Slides to go to next Page

My application starts by showing some Intro slides. 4 in total and in the last one, a button is used to close the slides and to go to the main page.
What I wish to make is to remove the button, and to make the last slide slidable. The user continues to slide to the right, and at the end it lands to the main page.
But don't know how to acheave that.
Here is the definition of
#interface IntroSlideViewController ()<ABCIntroViewDelegate>
#property ABCIntroView *introView;
#end
#implementation IntroSlideViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
-(void)viewDidAppear:(BOOL)animated{
/***************Page Control**************/
self.introView = [[ABCIntroView alloc] initWithFrame:self.view.frame];
self.introView.delegate = self;
self.introView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.000];
[self.view addSubview:self.introView];
/***************************************/
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)onDoneButtonPressed {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:FIRSTTIME_LOGIN];
InitScreenViewController* initVc = [self.storyboard instantiateViewControllerWithIdentifier:#"initScreenViewController"];
UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:initVc];
[navVC setNavigationBarHidden:true];
[UIView transitionWithView:[AppDelegate getShareInstance].window duration:0.1f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
[AppDelegate getShareInstance].window.rootViewController = navVC;
}completion:nil];
}
#end
And the parent class ABCIntroViewDelegate:
#interface ABCIntroView () <UIScrollViewDelegate>
#property (strong, nonatomic) UIScrollView *scrollView;
#property (strong, nonatomic) UIPageControl *pageControl;
#property (strong, nonatomic) UIButton *doneButton;
#property (strong, nonatomic) UIView *viewOne;
#property (strong, nonatomic) UIView *viewTwo;
#property (strong, nonatomic) UIView *viewThree;
#property (strong, nonatomic) UIView *viewFour;
#property (strong, nonatomic) UIView *viewFive;
#end
#implementation ABCIntroView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
[self addSubview:self.scrollView];
[self addSubview:self.pageControl];
[self.scrollView addSubview:self.viewOne];
[self.scrollView addSubview:self.viewTwo];
[self.scrollView addSubview:self.viewThree];
[self.scrollView addSubview:self.viewFour];
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.showsVerticalScrollIndicator = NO;
//Done Button
//[self addSubview:self.doneButton];
}
return self;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = CGRectGetWidth(self.bounds);
CGFloat pageFraction = self.scrollView.contentOffset.x / pageWidth;
self.pageControl.currentPage = roundf(pageFraction);
}
-(UIView *)viewOne {
if (!_viewOne) {
_viewOne = [[UIView alloc] initWithFrame:self.frame];
UIImageView *imageview;
imageview = [[UIImageView alloc] initWithFrame:self.frame];
imageview.image = [UIImage imageNamed:#"intro_slide_0"];
[_viewOne addSubview:imageview];
}
return _viewOne;
}
-(UIView *)viewTwo {
if (!_viewTwo) {
CGFloat originWidth = self.frame.size.width;
CGFloat originHeight = self.frame.size.height;
_viewTwo = [[UIView alloc] initWithFrame:CGRectMake(originWidth, 0, originWidth, originHeight)];
UIImageView *imageviewTwo;
imageviewTwo = [[UIImageView alloc] initWithFrame:self.frame];
imageviewTwo.image = [UIImage imageNamed:#"intro_slide_1"];
[_viewTwo addSubview:imageviewTwo];
}
return _viewTwo;
}
-(UIView *)viewThree{
if (!_viewThree) {
CGFloat originWidth = self.frame.size.width;
CGFloat originHeight = self.frame.size.height;
_viewThree = [[UIView alloc] initWithFrame:CGRectMake(originWidth*2, 0, originWidth, originHeight)];
UIImageView *imageviewThree;
imageviewThree = [[UIImageView alloc] initWithFrame:self.frame];
imageviewThree.image = [UIImage imageNamed:#"intro_slide_2"];
[_viewThree addSubview:imageviewThree];
}
return _viewThree;
}
-(UIView *)viewFour {
if (!_viewFour) {
CGFloat originWidth = self.frame.size.width;
CGFloat originHeight = self.frame.size.height;
_viewFour = [[UIView alloc] initWithFrame:CGRectMake(originWidth*3, 0, originWidth, originHeight)];
UIImageView *imageviewFour;
imageviewFour = [[UIImageView alloc] initWithFrame:self.frame];
imageviewFour.image = [UIImage imageNamed:#"intro_slide_3"];
[_viewFour addSubview:imageviewFour];
UIButton *btnDone = [[UIButton alloc] initWithFrame:CGRectMake(30, self.frame.size.height - 130, self.frame.size.width-60, 50)];
[btnDone setImage:[UIImage imageNamed:#"slide_3_button_unpressed"] forState:UIControlStateNormal];
[btnDone setImage:[UIImage imageNamed:#"slide_3_button_pressed"] forState:UIControlStateHighlighted];
[btnDone addTarget:self.delegate action:#selector(onDoneButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[_viewFour addSubview:btnDone];
}
return _viewFour;
}
-(UIView *)viewFive {
if (!_viewFive) {
}
return _viewFive;
}
-(UIScrollView *)scrollView {
if (!_scrollView) {
_scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
[_scrollView setDelegate:self];
[_scrollView setPagingEnabled:YES];
[_scrollView setContentSize:CGSizeMake(self.frame.size.width*numberofPage, self.scrollView.frame.size.height)];
[self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
return _scrollView;
}
-(UIPageControl *)pageControl {
if (!_pageControl) {
_pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height-20, self.frame.size.width, 10)];
//[_pageControl setCurrentPageIndicatorTintColor:UIColorFromRGBAlpha(252, 61, 136, 1)];
//[_pageControl setPageIndicatorTintColor:UIColorFromRGBAlpha(223, 227, 232, 1)];
[_pageControl setNumberOfPages:numberofPage];
}
return _pageControl;
}
-(UIButton *)doneButton {
if (!_doneButton) {
_doneButton = [[UIButton alloc] initWithFrame:CGRectMake(0, self.frame.size.height-60, self.frame.size.width, 100)];
[_doneButton setTintColor:[UIColor whiteColor]];
// [_doneButton.titleLabel setFont:FONT_Regular(17)];
[_doneButton setBackgroundColor:[UIColor colorWithRed:96/255.0 green:167/255.0 blue:23/255.0 alpha:1]];
[_doneButton addTarget:self.delegate action:#selector(onDoneButtonPressed) forControlEvents:UIControlEventTouchUpInside];
}
return _doneButton;
}
#end
Maybe what I am asking is not possible to be implemented.
Any clues and ideas are welcome
You can easily achieve your requirement by modifying ABCIntroView class. From ABCIntroView you are getting the callback as - (void)onDoneButtonPressed to IntroSlideViewController so there you are navigating to MainViewController.
So follow up these steps to achieve your requirement
Remove done button code from ABCIntroView.
Modify the below function.
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat pageWidth = CGRectGetWidth(self.bounds);
CGFloat pageFraction = self.scrollView.contentOffset.x/pageWidth;
self.pageControl.currentPage = roundf(pageFraction);
if (self.delegate != nil && self.pageControl.currentPage == 4){
[self.delegate onDoneButtonPressed];
}}

Change button's background colour

I am working on a project in which I create a subclass for UIButton for setting the gradient background colour.Its working fine but now there are two tabs in a ViewController there is two buttons suppose A and B. I want to change colour of button A when I clicked on Button B same like tabs functionality:
Sub class of UIButton:
// .h_file
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface grediantButton : UIButton
#property(nonatomic)IBInspectable UIColor*topColor;
#property(nonatomic)IBInspectable UIColor*bottomColor;
#property(nonatomic)IBInspectable CGFloat cornerRadius;
- (void)customInit;
#end
// .m file
#import "grediantButton.h"
#import "UIColor+myColor.h"
#implementation grediantButton
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.topColor = [UIColor clearColor];
self.bottomColor = [UIColor clearColor];
self.cornerRadius = 1;
[self customInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
- (void)drawRect:(CGRect)rect {
[self customInit];
}
- (void)setNeedsLayout {
[super setNeedsLayout];
[self setNeedsDisplay];
}
- (void)prepareForInterfaceBuilder {
[self customInit];
}
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
[self.layer insertSublayer:gradientLayer atIndex:0];
}
My VC Code:
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor getTabTopColor]];
[self.addnewTwnBtn setBottomColor:[UIColor getTabBotColor]];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(id)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn setTopColor:[UIColor getTabTopColor]];
[self.viewalltownBtn setBottomColor:[UIColor getTabBotColor]];
}
Tabs is like:
what happen when I click on black one tab
You should set state for UIButton multiple states.
For example, set different background images for different states.
[button setBackgroundImage:naomalImage forState:UIControlStateNormal];
[button setBackgroundImage:selectedImage forState:UIControlStateSelected];
And then, just control states.
- (IBAction)addnewTownShip:(id)sender {
button.selected = YES;
}
...
Thank you all for response.
I solved my issue by change some code in my - (void)customInit method
- (void)customInit {
self.layer.cornerRadius = self.cornerRadius;
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
gradientLayer.cornerRadius = self.cornerRadius;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[self.topColor CGColor], (id)[self.bottomColor CGColor],nil];
[self.layer setMasksToBounds:YES];
if([[self.layer sublayers] objectAtIndex:0]){
[self.layer replaceSublayer:[[self.layer sublayers] objectAtIndex:0] with:gradientLayer];
}else{
[self.layer insertSublayer:gradientLayer atIndex:0];
}
}
and call this method in
#pragma mark:AddnewTownshipVC
- (IBAction)addnewTownShip:(grediantButton*)sender {
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
[self.viewalltownBtn setTopColor:[UIColor blackColor]];
[self.viewalltownBtn setBottomColor:[UIColor blackColor]];
[self.viewalltownBtn customInit];
// sender.isSelected = true;
// self.viewalltownBtn.isSelected = false;
}
#pragma mark:viewalltownshipVC
- (IBAction)viewAllTownship:(grediantButton*)sender {
[self.addnewTwnBtn setTopColor:[UIColor blackColor]];
[self.addnewTwnBtn setBottomColor:[UIColor blackColor]];
[self.addnewTwnBtn customInit];
[sender setTopColor:[UIColor getTabTopColor]];
[sender setBottomColor:[UIColor getTabBotColor]];
[sender customInit];
}
simply go to the attribute inspector in storyboard see in bottom in it there has background colour you can change with it.
see here :-
https://i.stack.imgur.com/A6ecY.png

UITextField from enterBackground to enterForeground,app crash

custom UITextField: In the click TextField input,After the keyborad popup,enter the background to get enter foreground again,The app crash!
if you don't click TextField input,background or foreground conversion ,It is normal;Part of the code:
#implementatio BKSearchViewController
- (void)setNavgationView {
BKSearchBar *searchBar = [[BKSearchBar alloc] initWithFrame:CGRectMake(20, 27, kScreenWidth - 90, 30)];
searchBar.placeholder = #"输入昵称/拜托号";
searchBar.delegate = self;
[searchBar setKeyboardType:UIKeyboardTypeDefault];
[searchBar setReturnKeyType:UIReturnKeySearch];
[searchBar setPlaceholderColor:kcallColor(#"a4a4a4")];
[searchBar setPlaceholderFont:kFont(14)];
[searchBar addTarget:self action:#selector(SearchTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[navgationView addSubview:searchBar];
}
#end
//BKSearchBar The key code
#implementation BKSearchBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 设置背景
self.backgroundColor = kcallColor(#"7d1d57");
self.returnKeyType = UIReturnKeySearch;
// 设置内容 -- 垂直居中
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self UI];
}
return self;
}
- (void)UI{
// 设置左边显示一个放大镜
UIImageView *leftView = [[UIImageView alloc] init];
omit...
//右边的view
UIImageView *rightView = [[UIImageView alloc] init];
omit...
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds{
CGRect rect = CGRectMake(self.leftView.right, (self.height - 24) / 2, bounds.size.width, 14);
return rect;
}
- (void)clearText{
self.text = nil;
}
- (void)setPlaceholderColor:(UIColor *)color{
[self setValue:color forKeyPath:#"_placeholderLabel.textColor"];
}
- (void)setPlaceholderFont:(UIFont *)font{
[self setValue:font forKeyPath:#"_placeholderLabel.font"];
}
Thank all!The problem is resolved!because of the runtime!
+ (void)swizzleInstanceMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
Method otherMehtod = class_getInstanceMethod(class, otherSelector);
Method originMehtod = class_getInstanceMethod(class, originSelector);
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}

Memory getting increased everytime I am going into this view and I cant use arc in this code

Every time I am entering the same view memory is increasing. Even I am releasing nothing is happening and I can't use ARC due to older app issue. Don't know how to solve this issue.
#import <UIKit/UIKit.h>
#import "CareServices.h"
#interface AttachedImage : UIViewController<ServerConnectionDelegate,UIScrollViewDelegate>
{
IBOutlet UIImageView *imageView;
CareServices *careServices;
UIScrollView *_scrollView;
UIView *activityView;
UIActivityIndicatorView *_activity;
}
#property (nonatomic,retain)UIImageView *imageView;
#end
#import "AttachedImage.h"
#import"XMLParserForOtherAttachments.h"
#import "ColorSchemes.h"
#implementation AttachedImage
#synthesize imageView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
activityView = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2.5,self.view.frame.size.height/2.5, 60, 60)];
activityView.backgroundColor = [UIColor clearColor];
[self.view addSubview:activityView];
UIImageView *activityImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, activityView.frame.size.width, activityView.frame.size.height)];
activityImageView.image = [UIImage imageNamed:#"indicatorImage.jpeg"];
[activityView addSubview:activityImageView];
[activityImageView release];
_activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[_activity setFrame:CGRectMake(activityView.frame.size.width/5.8, activityView.frame.size.height/5.3, 40, 40)];
[activityView addSubview:_activity];
[_activity startAnimating];
[_activity release];
careServices = [CareServices currentInstance];
careServices.delegate = self;
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[super viewDidLoad];
self.navigationItem.title = #"Attachment View";
// self.view.backgroundColor = [ColorSchemes sharedInstance].primaryColor1;
self.view.backgroundColor = [UIColor blackColor];;
// Do any additional setup after loading the view from its nib.
}
-(void)viewDidAppear:(BOOL)animated {
NSString *senderTagStr;
NSUserDefaults *senderD = [NSUserDefaults standardUserDefaults];
senderTagStr = [senderD valueForKey:#"sender tag"];
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_scrollView.maximumZoomScale = 4.0;
_scrollView.minimumZoomScale = 1.0;
_scrollView.delegate = self;
_scrollView.contentSize = CGSizeMake(400, 500);
if (careServices.loginMode == ELoginModeDemo) {
if ([senderTagStr isEqualToString:#"0"]) {
imageView.image = [UIImage imageNamed:#"R1.bmp"];
}
else {
imageView.image = [UIImage imageNamed:#"8.jpg"];
}
}
else {
NSString *str = [NSString stringWithString:[XMLParserForOtherAttachments sharedManager].fileURlStr];
NSString *trimmedStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSData *imgData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:trimmedStr]];
UIImage *myImage = [UIImage imageWithData:imgData];
imageView.image = myImage;
[imgData release];
}
[_scrollView addSubview:imageView];
[self.view addSubview:_scrollView];
[_activity stopAnimating];
[activityView removeFromSuperview];
}
- (void)viewDidUnload {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
self.imageView = nil;
[super viewDidUnload];
}
- (void)dealloc{
[imageView release];
[super dealloc];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imageView;
}
#end
Locating the offending allocations/implementations is quite easy once you learn to use Heapshot Analysis.
Heapshot Analysis allows you to take snapshots during your execution in order to detect growths over a period of time, which you can of course associate with user actions in many cases. So you could for example push a view controller onto the navigation stack in iOS, then step back and easily determine what the growth was in doing so. Then navigate to the implementations which caused the growths.

Refactor iOS ViewController to work without needing a nib

I wrote a nice gallery view controller .h .m and .xib that work fine for my purposes. Tap a programmatically created button and load an image, play a movie or view a pdf or website - while in an existing uinavigationcontroller. I want to change it so I can add the contents of the xib in code - without using the nib file. In this way it will be more useable (I think).
The problem is the functions in the .m that reference, for instance - [self presentMoviePlayerViewControllerAnimated:YES] etc do not work. I tried making a property of the rootviewcontroller in this new .h and .m and replacing self with myController (property name). But my view controller code relies on uinavigation existing to push new content or things like that. How can I remove/tweak these references to self or a reliance on uinavigationcontrollers so it will work like when it has a view controller for a nib?
Edit: Code added below. In the nib there is just a uiscrollview called uis_thumbScrollView. I would like to add this anywhere by simply calling something like:
[self.view addSubview:[[ebThumbScroller alloc] initWithFrame:CGRectMake(0, 0, 1024, 733)]];
Everyone's comments reminded me that the uiview this will be put in exists within the rootviewcontroller, over the top. Maybe this is why I can hear the movie playing - but not see it.
Note: The code creates a series of uiviews with buttons inside of a uiscrollview.
.h
#import
#import "ebAppDelegate.h"
#import "MediaPlayer/MediaPlayer.h"
#interface HomeGalleryViewController : UIViewController <UIScrollViewDelegate, UIGestureRecognizerDelegate, UIDocumentInteractionControllerDelegate> {
BOOL pageControlBeingUsed;
int buttonCount;
CGFloat _minimumColumnGap;
UIEdgeInsets _contentInsets;
NSInteger _colCount;
NSInteger _rowCount;
CGFloat _rowGap;
CGFloat _colGap;
UIEdgeInsets _effectiveInsets;
//int iGalleryThumbs;
//int iPlanThumbs;
int iTotalButtons;
ebAppDelegate *ebappdelegate;
ebGalleryItem *ebgalleryItem;
NSDictionary *gallDict;
NSArray *gallerySections;
NSArray *galleryArray;
NSMutableArray *nsm_gallArray;
UIDocumentInteractionController *controller;
}
//#property (nonatomic, retain) IBOutlet UIButton *bItem;
#property (nonatomic, retain) NSString *galleryNameString;
#property (nonatomic, retain) IBOutlet UIScrollView* scrollView;
#property (retain, nonatomic) NSMutableArray *arr_Views;
#property (strong, nonatomic) IBOutlet UIScrollView* uis_thumbScrollView;
#property (strong, nonatomic) IBOutlet UIPageControl* uis_pageControl;
#property (strong, nonatomic) IBOutlet UIView *uiv_thumbView;
#property (strong, nonatomic) MPMoviePlayerController *player;
#property (strong, nonatomic) MPMoviePlayerViewController *playerViewController;
- (IBAction)changePage;
- (IBAction) clickOpen:(id)sender;
- (void)playMovie:(NSString*)movieName;
- (void)movieFinishedCallback:(NSNotification*)_notification;
#end
.m
#import "HomeGalleryViewController.h"
#import "ebAppDelegate.h"
#import "GalleryImagesViewController.h"
#import "Gallery.h"
#import "GalleryThumbnailsViewController.h"
#import "GalleriesListViewController.h"
#import <QuartzCore/CoreAnimation.h>
#import "ebGalleryItem.h"
#import "WebViewController.h"
#implementation HomeGalleryViewController
// buttons
#define hGutter 17
#define vGutter 13
#define btnSize 130
#define topSpace 50
#define leftMargin 100
#synthesize uiv_thumbView;
#synthesize uiv_gallCat0, uiv_gallCat1, uiv_gallCat2,uiv_gallCat3, uiv_gallCat4, uiv_gallCat5,uiv_gallCat6;
#synthesize uis_thumbScrollView, uis_pageControl;
#synthesize galleryNameString,scrollView,arr_Views;
#synthesize player, playerViewController;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
ebappdelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate];
arr_Views = [[NSMutableArray alloc] init];
self.scrollView.contentSize = CGSizeMake(1024, 1005);
// nsarray of dictionaries (galleries)
gallerySections = ebappdelegate.arr_galleryData;
NSLog(#"gallerySections count:%i",[gallerySections count]);
nsm_gallArray = [NSMutableArray arrayWithCapacity:1];
[self layoutGalleryThumbs];
}
#pragma mark
#pragma mark Layout Gallery Thumbs
-(void)layoutGalleryThumbs {
NSUInteger numGallSections = [gallerySections count];
NSLog(#"gallerySections data:%#",gallerySections);
NSLog(#"numGallSections count:%i",numGallSections);
// Window bounds.
CGRect bounds = CGRectMake(0, 0, 1024, 215);
for (int i=0; i<numGallSections; i++) {
// Create a view and add it to the window.
UIView* vview = [[UIView alloc] initWithFrame: CGRectMake(0, bounds.size.height*i-1, bounds.size.width, bounds.size.height)];
[vview setBackgroundColor: [UIColor whiteColor]];
[vview setTag:i];
//vview.backgroundColor = (UIColor (i % 2 == 0 ? cyanColor : whiteColor];
vview.backgroundColor = (i % 2 == 0)? [UIColor lightGrayColor] : [UIColor whiteColor];
[arr_Views addObject:vview];
// add line below at bottom
UIView* lineView = [[UIView alloc] initWithFrame: CGRectMake(280, bounds.size.height, 700, 2)];
[lineView setBackgroundColor: [UIColor grayColor]];
lineView.alpha = 0.5;
[vview addSubview:lineView];
[uis_thumbScrollView addSubview: vview];
NSLog(#"start===============i:%i",i);
// grab a gallery
gallDict = [gallerySections objectAtIndex:i]; // grab dict
galleryArray = [gallDict objectForKey:#"gallSectionData"]; // grab array from dict
NSLog(#"galleryArray:%#",[galleryArray description]);
NSString *secTitle = [gallDict objectForKey:#"gallSectionName"];
iTotalButtons = [galleryArray count];
NSLog(#"iTotalButtons count:%i",iTotalButtons);
_minimumColumnGap = 5;
_colCount = floorf((uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right) / btnSize);
while (1) {
_colGap = (uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right - btnSize * _colCount) / (_colCount + 1);
if (_colGap >= _minimumColumnGap)
break;
--_colCount;
};
_rowCount = (iTotalButtons + _colCount - 1) / _colCount;
_rowGap = _colGap;
_effectiveInsets = UIEdgeInsetsMake(_contentInsets.top + _rowGap,
_contentInsets.left + _colGap,
_contentInsets.bottom + _rowGap,
_contentInsets.right + _colGap);
NSLog(#"row count:%i",_rowCount);
NSLog(#"col count:%i",_colCount);
buttonCount=0;
for (int e=0; e<iTotalButtons; e++) {
NSLog(#"e:%i",e);
ebgalleryItem = [galleryArray objectAtIndex:e];
UIImage *thumbImg = [UIImage imageNamed:ebgalleryItem.gallThumb];
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
CGRect frame = CGRectMake (btnSize*e+leftMargin, topSpace,
btnSize-hGutter, btnSize-vGutter );
[button setFrame: frame];
NSLog(#"added button");
//[button setBackgroundImage:thumbImg forState:UIControlStateNormal];
[button setImage:thumbImg forState:UIControlStateNormal];
[button setTitle:ebgalleryItem.gallName forState:UIControlStateNormal];
NSLog(#"%#",button.titleLabel.text);
[button addTarget: NULL action:#selector(clickOpen:) forControlEvents:UIControlEventTouchUpInside];
UILongPressGestureRecognizer *tapAndHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longclickOpen:)];
[tapAndHold setMinimumPressDuration:0.33];
[button addGestureRecognizer:tapAndHold];
[button setTag:e];
//[button setTag:i*_colCount+e];
NSLog(#" button tag=%i", button.tag);
button.alpha=1.0;
[[arr_Views objectAtIndex:i] addSubview:button];
NSLog(#"middle====i:%i",i);
// caption label
CGRect labelFrame = CGRectMake( btnSize*e+leftMargin, 125,
btnSize-hGutter, btnSize-vGutter );
UILabel* label = [[UILabel alloc] initWithFrame: labelFrame];
[label setFont:[UIFont fontWithName:#"Arial" size:14]];
label.numberOfLines = 0;
[label setText:ebgalleryItem.gallCaption];
[label setTextColor: [UIColor blackColor]];
[label setTextAlignment:UITextAlignmentCenter];
[label setBackgroundColor:[UIColor clearColor]];
[[arr_Views objectAtIndex:i] addSubview: label];
NSLog(#"middle2====i:%i",i);
buttonCount++;
}
// Section Title label
CGRect titleLabelFrame = CGRectMake(btnSize,0,250,50);
UILabel* titlelabel = [[UILabel alloc] initWithFrame: titleLabelFrame];
[titlelabel setFont:[UIFont fontWithName:#"Arial" size:16]];
[titlelabel setText:secTitle];
[titlelabel setTextColor: [UIColor blackColor]];
[titlelabel setTextAlignment:UITextAlignmentLeft];
[titlelabel setBackgroundColor:[UIColor clearColor]];
[[arr_Views objectAtIndex:i] addSubview: titlelabel];
NSLog(#"end====i:%i",i);
CGFloat scrollViewHeight = 0.0f;
for (UIView* view in self.uis_thumbScrollView.subviews)
{
if (!view.hidden)
{
CGFloat y = view.frame.origin.y;
CGFloat h = view.frame.size.height;
if (y + h > scrollViewHeight)
{
scrollViewHeight = h + y;
}
}
}
[self.uis_thumbScrollView setContentSize:(CGSizeMake(self.uis_thumbScrollView.frame.size.width, scrollViewHeight+74))]; //74 is space from top in IB of scroll
}
uiv_thumbView.alpha = 1.0;
}
#pragma mark Scrollview
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.uis_thumbScrollView.frame.size.width;
int page = floor((self.uis_thumbScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.uis_pageControl.currentPage = page;
// nslogs zoomsacle/bounds
CGRect visibleRect;
visibleRect.origin = uis_thumbScrollView.contentOffset;
visibleRect.size = uis_thumbScrollView.bounds.size;
float theScale = 1.0 / [uis_thumbScrollView zoomScale];
visibleRect.origin.x *= theScale;
visibleRect.origin.y *= theScale;
visibleRect.size.width *= theScale;
visibleRect.size.height *= theScale;
NSLog( #"Visible rect: %#", NSStringFromCGRect(visibleRect) );
}
- (IBAction)changePage {
// update the scroll view to the appropriate page
CGRect frame;
frame.origin.x = self.uis_thumbScrollView.frame.size.width * self.uis_pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.uis_thumbScrollView.frame.size;
[self.uis_thumbScrollView scrollRectToVisible:frame animated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
//===================================================================
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft | interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[self setUiv_thumbView:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (void)viewWillAppear:(BOOL)animated {
[UIApplication sharedApplication].statusBarHidden = YES;
self.view.frame = [UIScreen mainScreen].applicationFrame;
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = 0;
self.navigationController.navigationBar.frame = frame;
[self.navigationController setNavigationBarHidden:YES animated:animated];
self.navigationController.navigationBar.translucent = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[UIApplication sharedApplication].statusBarHidden = NO;
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = 20.0;
self.navigationController.navigationBar.frame = frame;
}
- (void)viewDidAppear:(BOOL)animated {
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[self.navigationController setNavigationBarHidden:YES animated:animated];
[self.navigationController setToolbarHidden:YES animated:YES];
[super viewDidAppear:animated];
}
//======================================================================
-(IBAction)clickOpen:(id)sender {
UIButton *tmpBtn = (UIButton*)sender;
NSLog(#"sender tag: %i", [sender tag]);
int superviewTag = [sender superview].tag;
NSLog(#"sender superview tag: %i", superviewTag);
gallDict = [gallerySections objectAtIndex:superviewTag]; // grab dict
galleryArray = [gallDict objectForKey:#"gallSectionData"]; // grab array from dict
tmpBtn.alpha = 0.6;
ebgalleryItem = [galleryArray objectAtIndex:[sender tag]];
NSLog(#"%#",ebgalleryItem.gallType);
NSLog(#"%#",ebgalleryItem.gallName);
NSLog(#"gallDict %#",gallDict);
if ([ebgalleryItem.gallType isEqualToString:#"movie"]) {
[self playMovie:ebgalleryItem.gallFilm];
} else if ([ebgalleryItem.gallType isEqualToString:#"image"]) {
[self imageViewer:sender];
} else if ([ebgalleryItem.gallType isEqualToString:#"pdf"]) {
[self viewPDF:ebgalleryItem.gallName];
} else if ([ebgalleryItem.gallType isEqualToString:#"web"]) {
[self openWeb:ebgalleryItem.gallName];
}
}
#pragma mark
#pragma mark Open Websites
- (IBAction)openWeb:(NSString*)thisWEB {
WebViewController *webViewController = [[WebViewController alloc]
initWithNibName:#"WebViewController"
bundle:nil];
[webViewController socialButton:thisWEB];
webViewController.title = thisWEB;
[self presentModalViewController:webViewController animated:YES];
}
#pragma mark
#pragma mark Image Viewer
-(void)imageViewer:(id)sender {
UIButton *tmpBtn = (UIButton*)sender;
galleryNameString = tmpBtn.titleLabel.text;
tmpBtn.alpha = 0.6;
GalleryImagesViewController *vc = [[GalleryImagesViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]];
[vc goToPageAtIndex:0 animated:NO];
CATransition* transition = [CATransition animation];
transition.duration = 0.33;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer
addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:vc animated:NO];
}
#pragma mark
#pragma mark PDF Viewer
-(void)viewPDF:(NSString*)thisPDF {
NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:thisPDF ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:fileToOpen];
NSLog(#"%#",fileToOpen);
controller = [UIDocumentInteractionController interactionControllerWithURL:url];
[self previewDocumentWithURL:url];
}
- (IBAction) clickClose:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
- (void)previewDocumentWithURL:(NSURL*)url
{
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
}
//======================================================================
- (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{
}
//===================================================================
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
return self.view.frame;
}
-(IBAction)longclickOpen:(UILongPressGestureRecognizer*)gesture {
if (gesture.state == UIGestureRecognizerStateBegan ) {
[self.navigationController setNavigationBarHidden:NO];
ebAppDelegate *appDelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.isFromLongPress=YES;
//NSUInteger i = [gesture.view tag];
//galleryNameString = [appDelegate.arr_galleryData objectAtIndex:i];
NSLog(#"load %#",galleryNameString);
UIButton *btn = (UIButton*)gesture.view;
galleryNameString = btn.titleLabel.text; btn.alpha = 0.6;
//NSLog(#"Long Press");
//NSLog(#"llongclickOpen");
UIViewController *vc = [[GalleryThumbnailsViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]];
CATransition* transition = [CATransition animation];
transition.duration = 0.33;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer
addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:vc animated:NO];
}
}
-(void)playMovie:(NSString*)movieName {
NSString *url = [[NSBundle mainBundle]
pathForResource:movieName
ofType:#"m4v"];
NSLog(#"%#",movieName);
playerViewController = [[MPMoviePlayerViewController alloc]
initWithContentURL:[NSURL fileURLWithPath:url]];
[[NSNotificationCenter defaultCenter] removeObserver:playerViewController
name:MPMoviePlayerPlaybackDidFinishNotification
object:playerViewController.moviePlayer];
// Register this class as an observer instead
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:playerViewController.moviePlayer];
[self.view insertSubview:playerViewController.view atIndex:50];
//---play movie---
player = [playerViewController moviePlayer];
player.controlStyle = MPMovieControlStyleFullscreen;
player.repeatMode=MPMovieRepeatModeOne;
[self presentMoviePlayerViewControllerAnimated:playerViewController];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[super viewDidLoad];
}
- (void)movieFinishedCallback:(NSNotification*)aNotification {
// Obtain the reason why the movie playback finished
NSNumber *finishReason = [[aNotification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
// Dismiss the view controller ONLY when the reason is not "playback ended"
if ([finishReason intValue] != MPMovieFinishReasonPlaybackEnded)
{
MPMoviePlayerController *moviePlayer = [aNotification object];
// Remove this class from the observers
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayer];
// Dismiss the view controller
[self dismissModalViewControllerAnimated:YES];
}
}
#end
If your only problem is the not working [self presentMoviePlayerViewControllerAnimated:YES] method, the problem is that presentMoviePlayerViewControllerAnimated: requires the actual moviePlayerViewController as an argument not a boolean value. (assuming you're refering to this method of the UIViewController category) UIViewController MediaPlayer Additions Reference
So if you replace that by say presentMoviePlayerViewControllerAnimated:self.moviePlayerVC, it should work as expected.
I'm not sure I understand your question, but if you need to wrap your controller to some UINavigationController you can do it like this:
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.navigationBar.barStyle = UIBarStyleBlack;
[self presentViewController:navController animated:YES completion:^{
//
}];
later on any child controller will have the navigation hierarchy.

Resources