Core Animation Strange Display after addSubview then removeFromSuperview - ios

I have a view controller with a central container that gets flipped to show different views on each side. One of the views is a table view and the other is a custom view of mine. It is working perfectly as per screenshot 1.
My problem is that after I have added a subview over this viewcontroller (its a transparent UIView for showing help screen) and then remove this subview from the viewcontroller
, when I try re-flip the central view strange results occur. There still seems to be a flipping animation between the two views, but as you can see from the last 2 screenshot an extra central table view just sits there. I can't quite explain this exactly so I'm hoping a combination of the pictures, and some code will help:
MainPageVC.h
#interface MainPageVC : UIViewController <UITableViewDataSource, UITableViewDelegate>
#end
MainPageVC.m
#interface MainPageVC ()
#property (nonatomic, strong) NSArray *dataArr;
#property (nonatomic, weak) IBOutlet UIView *flipContainerView;
#property (nonatomic, strong) UIView *detailFlipView;
#property (nonatomic, strong) UITableView *listFlipView;
#property (nonatomic) BOOL isTransitioning;
#property (nonatomic) BOOL isFlipped;
#end
#implementation MainPageVC
#synthesize dataArr = _dataArr;
#synthesize flipContainerView = _flipContainerView;
#synthesize detailFlipView = _detailFlipView;
#synthesize listFlipView = _listFlipView;
#synthesize isTransitioning = _isTransitioning;
#synthesize isFlipped = _isFlipped;
- (void)viewDidLoad {
[super viewDidLoad];
self.dataArr = [NSArray arrayWithObjects:#"row 1", #"row 2", #"row 3", nil];;
}
- (void)viewDidLayoutSubviews {
[self setUpCustomViews];
}
- (void)setUpCustomViews {
self.isFlipped = NO;
self.isTransitioning = NO;
CGRect frame = CGRectMake(0, 0, self.flipContainerView.frame.size.width, self.flipContainerView.frame.size.height);
self.detailFlipView = [[UIView alloc] initWithFrame:frame];
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,50,50)];
[self.detailFlipView addSubview:customView];
self.listFlipView = [[UITableView alloc] initWithFrame:frame];
self.listFlipView.delegate = self;
self.listFlipView.dataSource = self;
UIColor *backgroundColour = [UIColor whiteColor];
CGFloat cornerRadius = 15.0f;
CGFloat borderWidth = 1.5f;
UIColor *borderColour = [UIColor colorWithRed:49.0/255.0f green:49.0/255.0f blue:49.0/255.0f alpha:1.0f];
self.detailFlipView.backgroundColor = backgroundColour;
self.listFlipView.backgroundColor = backgroundColour;
self.detailFlipView.layer.cornerRadius = cornerRadius;
self.listFlipView.layer.cornerRadius = cornerRadius;
self.detailFlipView.layer.borderWidth = borderWidth;
self.listFlipView.layer.borderWidth = borderWidth;
self.detailFlipView.layer.borderColor = [borderColour CGColor];
self.listFlipView.layer.borderColor = [borderColour CGColor];
self.detailFlipView.layer.doubleSided = NO;
self.listFlipView.layer.doubleSided = NO;
self.listFlipView.layer.masksToBounds = YES;
self.detailFlipView.layer.masksToBounds = YES;
[self.flipContainerView addSubview:self.detailFlipView];
[self.flipContainerView addSubview:self.listFlipView];
}
- (IBAction)changeViewTapped:(UIControl *)sender {
if (self.isTransitioning) return;
CALayer *top = self.listFlipView.layer;
CALayer *bottom = self.detailFlipView.layer;
if (self.isFlipped) {
top = self.detailFlipView.layer;
bottom = self.listFlipView.layer;
}
CAAnimation *topAnimation = [self flipAnimationWithDuration:0.6f forLayerBeginningOnTop:YES scaleFactor:1.2f];
CAAnimation *bottomAnimation = [self flipAnimationWithDuration:0.6f forLayerBeginningOnTop:NO scaleFactor:1.2f];
CGFloat zDistance = 1000.0f;
CATransform3D perspective = CATransform3DIdentity;
perspective.m34 = -1. / zDistance;
top.transform = perspective;
bottom.transform = perspective;
topAnimation.delegate = self;
[CATransaction begin];
[top addAnimation:topAnimation forKey:#"flip"];
[bottom addAnimation:bottomAnimation forKey:#"flip"];
CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:#"backgroundColor"];
colorAnimation.toValue = (id)[UIColor colorWithRed:27.0/255.0f green:47.0/255.0f blue:87.0/255.0f alpha:1.0f].CGColor;
[self.bannerButtonImageView.layer addAnimation:colorAnimation forKey:#"colorAnimation"];
[CATransaction commit];
}
-(CAAnimation *)flipAnimationWithDuration:(NSTimeInterval)aDuration forLayerBeginningOnTop:(BOOL)beginsOnTop scaleFactor:(CGFloat)scaleFactor {
self.isTransitioning = YES;
CABasicAnimation *flipAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.y"];
CGFloat startValue = beginsOnTop ? 0.0f : M_PI;
CGFloat endValue = beginsOnTop ? -M_PI : 0.0f;
flipAnimation.fromValue = [NSNumber numberWithDouble:startValue];
flipAnimation.toValue = [NSNumber numberWithDouble:endValue];
CABasicAnimation *shrinkAnimation = nil;
if (scaleFactor != 1.0f ) {
shrinkAnimation = [CABasicAnimation animationWithKeyPath:#"transform.scale"];
shrinkAnimation.toValue = [NSNumber numberWithFloat:scaleFactor];
shrinkAnimation.duration = aDuration * 0.5;
shrinkAnimation.autoreverses = YES;
}
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.animations = [NSArray arrayWithObjects:flipAnimation, shrinkAnimation, nil];
animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animationGroup.duration = aDuration;
animationGroup.fillMode = kCAFillModeForwards;
animationGroup.removedOnCompletion = NO;
return animationGroup;
}
-(void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag {
self.isFlipped = !self.isFlipped;
self.isTransitioning = NO;
}
...USUAL UITABLEVIEW METHODS
- (void)showHelpScreen {
CustomHelp *helpView = [[CustomHelp alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:helpView];
}
#end
CustomHelp.h
#interface CustomHelp : UIView
#end
CustomHelp.m
#implementation CustomHelp
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 50, 100)];
test.backgroundColor = [UIColor redColor];
[self addSubview:test];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self addGestureRecognizer: singleTap];
}
return self;
}
- (void)handleSingleTap {
[UIView animateWithDuration:0.5
animations:^{ self.alpha = 0.0;}
completion:^(BOOL finished){
[self removeFromSuperview];
}];
}
#end

Adding comment as answer.
My only suggestion would be in the setUpCustomViews function to add in an if(!self.listFlipView) and if(!self.detailFlipView) to the view creation. That function may be being called multiple times and thereby adding multiple views to your window without removing the previous one.

Related

How can i display string instead of image in UIView?

Interface is define like this
#interface IGLDemoCustomView : UIView
#property (nonatomic, strong) UIImage *image;
#property (nonatomic, strong) NSString *title;
#end
While Implementation file look like this
#interface IGLDemoCustomView ()
#property (nonatomic, strong) UIImageView *imageView;
#property (nonatomic, strong) UILabel *titleLabel
#end
#implementation IGLDemoCustomView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit
{
[self initView];
}
- (void)initView
{
self.layer.borderColor = [UIColor colorWithRed:0.18 green:0.59 blue:0.69 alpha:1.0].CGColor;
self.layer.borderWidth = 2.0;
self.layer.masksToBounds = YES;
self.backgroundColor = [UIColor whiteColor];
self.alpha = 0.8;
UIImageView *imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeCenter;
[self addSubview:imageView];
self.imageView = imageView;
UILabel *titleLabel;
self.titleLabel = [[UILabel alloc]init];
titleLabel.center = self.center; // set proper frame for label
[self addSubview:titleLabel];
}
- (void)setImage:(UIImage *)image
{
_image = image;
self.imageView.image = image;
}
- (void)setString:(NSString *)title
{
self.title=title;
self.titleLabel.text = title;
}
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
self.imageView.frame = self.bounds;
self.layer.cornerRadius = frame.size.height / 2.0;
}
#end
When i select image from the drop down menu it shows in the menu, but when i select any text from the drop down menu it doesnt show in the drop down list view.
Any clue will be highly appreciated.
Calling and setting string in the view
IGLDropDownItem *menuButton = strongSelf.dropDownMenu.menuButton;
IGLDemoCustomView *buttonView = (IGLDemoCustomView*)menuButton.customView;
buttonView.title = device.name;
You need to set a frame for the label
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
self.imageView.frame = self.bounds;
self.titleLabel.frame = self.bounds;
self.layer.cornerRadius = frame.size.height / 2.0;
}
If you are expecting the text to wrap, you'll need to set the lineBreakMode and set numberOfLines to 0
Like you are having UIImageView you need to have a UILabel inside your UIView too.
#interface IGLDemoCustomView ()
#property (nonatomic, strong) UIImageView *imageView;
#property (nonatomic, strong) UILabel *titleLabel;
#end
- (void)initView
{
self.layer.borderColor = [UIColor colorWithRed:0.18 green:0.59 blue:0.69 alpha:1.0].CGColor;
self.layer.borderWidth = 2.0;
self.layer.masksToBounds = YES;
self.backgroundColor = [UIColor whiteColor];
self.alpha = 0.8;
UIImageView *imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeCenter;
[self addSubview:imageView];
self.imageView = imageView;
self.titleLabel = [[UILabel alloc]init];
titleLabel.center = self.center; // set proper frame for label
[self addSubview:titleLabel]
}
And in setString
- (void)setString:(NSString *)title
{
self.title=title;
self.titleLabel.text = title;
}

animation not works in the non-initial UIViewController

I have a UIView called loadingView shows some UIActivityIndicatorView-like animation. There are two UIViewControllers that all have such UIView.
The initial UIViewController's code:
- (void)viewDidLoad {
self.loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(10, 1, 120, 120)];
[self.view addSubview:self.loadingView];
}
Also it has a button to present the second UIViewController:
- (void)buttonPressed {
SecondViewController *sVC = [[SecondViewController alloc] init];
[self presentViewController:sVC animated:YES completion:nil];
}
The second ViewController's viewDidLoad method code:
- (void)viewDidLoad {
self.loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(10, 1, 120, 120)];
[self.view addSubview:self.loadingView];
}
As you can see, the two UIViewControllers has the same viewDidLoad method code.
The loadingView works well in the initial UIViewController.
But in the second UIViewController, the loadingView only displays the black frame( I set the background colour to black).
Here is my loadingView implement code:
#define NUMBER_OF_DOT 15
#define DURATION 1.5
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.replicatorLayer = [[CAReplicatorLayer alloc] init];
self.replicatorLayer.frame = frame;
self.replicatorLayer.cornerRadius = 10.0;
self.replicatorLayer.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.86].CGColor;
self.replicatorLayer.position = self.center;
self.replicatorLayer.instanceDelay = DURATION/NUMBER_OF_DOT;
[self.layer addSublayer:self.replicatorLayer];
float size = frame.size.width*14/200;
self.dot = [[CALayer alloc] init];
self.dot.bounds = CGRectMake(0, 0, size, size);
self.dot.position = CGPointMake(frame.size.width/2, frame.size.height/5);
self.dot.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0].CGColor;
self.dot.borderColor = [UIColor whiteColor].CGColor;
self.dot.borderWidth = 1.0;
self.dot.cornerRadius = 1.5;
self.dot.transform = CATransform3DMakeScale(0.01, 0.01, 0.01);
[self.replicatorLayer addSublayer:self.dot];
self.replicatorLayer.instanceCount = NUMBER_OF_DOT;
float angle = 2*M_PI/NUMBER_OF_DOT;
self.replicatorLayer.instanceTransform = CATransform3DMakeRotation(angle, 0.0, 0.0, 0.1);
self.shrink = [[CABasicAnimation alloc] init];
self.shrink.keyPath = #"transform.scale";
self.shrink.fromValue = [NSNumber numberWithFloat:1.0];
self.shrink.toValue = [NSNumber numberWithFloat:0.1];
self.shrink.duration = DURATION;
self.shrink.repeatCount = INFINITY;
[self.dot addAnimation:self.shrink forKey:nil];
}
return self;
}
-(void)viewDidAppear:(BOOL)animated
{
self.loadingView = [[LoadingView alloc] initWithFrame:CGRectMake(10, 1, 120, 120)];
[self.view addSubview:self.loadingView];
}
Put this code in viewDidAppear of SecondViewController so it works in present mode as well.

CALayer, subLayer alpha overriding

I have a CALayer ( superlayer ) with 0.3 opacity property. The superlayer contains another CALayer(sublayer). Although sublayer does not have a opacity property superLayer's opacity affects sublayer's appearance. Is there a method that I can override superLayer'a opacity property.
SuperLayer
#implementation SuperView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setOpaque:NO];
[self.layer setOpaque:NO];
}
return self;
}
-(void)drawRect:(CGRect)rect
{
CALayer* superLaer=self.layer;
superLaer.backgroundColor = [UIColor blackColor].CGColor;
superLaer.shadowOffset = CGSizeMake(0, 3);
superLaer.shadowRadius = 5.0;
superLaer.shadowColor = [UIColor blackColor].CGColor;
superLaer.shadowOpacity = 0.6;
superLaer.frame = CGRectMake(10, 10, 300,300);
superLaer.borderColor = [UIColor blackColor].CGColor;
superLaer.borderWidth = 2.0;
superLaer.cornerRadius = 10.0;
superLaer.cornerRadius = 10.0;
superLaer.masksToBounds=YES;
superLaer.opacity = 0.1;
}
#end
SubLayer
#implementation SubView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setOpaque:NO];
[self.layer setOpaque:NO];
}
return self;
}
-(void)drawRect:(CGRect)rect
{
CALayer* superLaer=self.layer;
superLaer.backgroundColor = [UIColor redColor].CGColor;
superLaer.shadowOffset = CGSizeMake(0, 3);
superLaer.shadowRadius = 5.0;
superLaer.shadowColor = [UIColor blackColor].CGColor;
superLaer.shadowOpacity = 0.6;
superLaer.frame = CGRectMake(100, 100, 100,100);
superLaer.borderColor = [UIColor blackColor].CGColor;
superLaer.borderWidth = 2.0;
superLaer.cornerRadius = 10.0;
superLaer.cornerRadius = 10.0;
superLaer.masksToBounds=YES;
}
#end
I have added the subView to the superView in Viewcontroller.
Based on your question, The super layer's opacity controls the sublayers' opacity,
you could subclass CALayer and override some of its properties in init method like
#implementation SomeSuperCALayer
-(id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
#define W_H 100.0
#define X_Y 50.0f
-(void)setup
{
self.frame = CGRectMake(X_Y, X_Y, W_H, W_H);
self.backgroundColor = [UIColor blueColor].CGColor;
self.opacity = 1.0f; // big opacity
}
#implementation SomeSubCALayer
-(id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
#define W_H 100.0
#define X_Y 150.0f
-(void)setup
{
self.frame = CGRectMake(X_Y, X_Y, W_H, W_H);
self.backgroundColor = [UIColor blueColor].CGColor;
self.opacity = .5f; // small opacity
}
# implementation MyViewController
//
-(void)viewDidLoad
{
SomeSuperCALayer *superLayer = [[SomeSuperCALayer alloc] init]; SomeSubCALayer *subLayer = [[SomeSubCALayer alloc] init];
//add sub layer to super layer
[superLayer addSubLayer:subLayer];
// add super layer to main View
[self.view.layer addSubLayer:superLayer];
//
//...
}
Also don't use drawRect for calling layer's properties, drawRect is mean't for drawing like the Apple's documentation dictates:
/ Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

Properties Accessor Method Implementation

I'm trying to make another custom view available at rood VC's viewdidload.
MSHView *customTextView = [[MSHView alloc] initWithFrame:self.view.bounds];
customTextView.textView.text = #"abc";
[customTextView layoutSubviews];
[self.view addSubview:customTextView];
MSHView Header file:
#property(nonatomic, strong) UITextView * textView;
#property (nonatomic, strong) UIImageView* translucentIV;
MSHView implementaion file:
-(UIImageView*) translucentIV {
if(!_translucentIV) {
_translucentIV.frame = self.frame;
//NSLog(#"frame for translucent IV, %#", _translucentIV.frame);
_translucentIV.backgroundColor = [UIColor whiteColor];
_translucentIV.alpha = 0.5;
}
return _translucentIV;
}
-(UITextView* ) textView{
if(!_textView){
/*
float height = self.bounds.size.height - 5;
float width = self.bounds.size.width - 5;
_textView.frame = CGRectMake(5,5,width,height);
_textView.text = #"test text";
*/
NSLog(#"textview property being initialized");
}
return _textView;
}
-(void)layoutSubviews {
self.textView.frame = self.frame;
self.translucentIV.backgroundColor = [UIColor whiteColor];
self.alpha = 0.5;
NSString *abc = #"abc";
self.textView.text = [NSString stringWithFormat:#"%#",abc];
NSLog(#"layout subview being called");
}
-(void) setTextView:(UITextView *)textView {
if(textView != _textView) {
_textView = textView;
_textView.text = #"setter method called";
}
}
Still cannot see the textview from MSHView. I think I'm not doing properties properly. any help or explanation?
Thanks in advance.
You are not creating the UIImageView and UITextView.
Try something more like:
-(UIImageView*) translucentIV {
if(!_translucentIV) {
_translucentIV = [[UIImageView alloc] initWithFrame:self.frame];
//NSLog(#"frame for translucent IV, %#", _translucentIV.frame);
_translucentIV.backgroundColor = [UIColor whiteColor];
_translucentIV.alpha = 0.5;
}
return _translucentIV;
}
-(UITextView *)textView {
if(!_textView) {
float height = self.bounds.size.height - 5;
float width = self.bounds.size.width - 5;
_textView = [[UITextView alloc] initWithFrame:CGRectMake(5,5,width,height)];
}
return _textView;
}
You'll also want to add them to the parent view somewhere.

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