Sliding Between UISegmentedControl Views - ios

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

Related

Switching of segment controller is not functioning in a UISegmentControl when called externally through selectedSegmentIndex

I am having a view controller with UISegment in it.
On clicking the segment controller instead of navigating to UIVIew I am using UIVIEWcontrolers.
Here is my code
.h file
#property (weak, nonatomic) IBOutlet UIView *containerView;
#property (weak, nonatomic) IBOutlet UISegmentedControl *segmenter;
- (IBAction)showComponent:(UISegmentedControl *)sender;
#property (weak, nonatomic) UIViewController *currentViewController;
-(void)loadViewFromData;
.m file
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if ([[appD.defaults objectForKey:#"segment"] isEqualToString:#"index0"]) {
self.currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr1"];
self.segmenter.selectedSegmentIndex = 0;
[self.segmenter sendActionsForControlEvents:UIControlEventValueChanged];
}else{
self.currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr2"];
self.segmenter.selectedSegmentIndex = 1;
[self.segmenter sendActionsForControlEvents:UIControlEventValueChanged];
}
// self.currentViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
// [self addChildViewController:self.currentViewController];
// [self addSubview:self.currentViewController.view toView:self.containerView];
// //[self changeSegment];
[self.segmenter addTarget:self action:#selector(changedSegmentedControl:) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view.
}
- (void)changedSegmentedControl:(UISegmentedControl*)sender
{
NSLog(#"Changed value of segmented control to %ld", sender.selectedSegmentIndex);
NSLog(#"self.segmenter value of segmented control to %ld", self.segmenter.selectedSegmentIndex);
// Code to change View Controller goes here
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
}
-(void)loadViewFromData{
// [self viewDidLoad];
// [self viewWillAppear:YES];
// [self reloadInputViews];
self.segmenter.selectedSegmentIndex = 1;
[self changedSegmentedControl:self.segmenter];
[self.segmenter sendActionsForControlEvents:UIControlEventValueChanged];
}
-(void)changeSegment{
AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if ([[appD.defaults objectForKey:#"segment"] isEqualToString:#"index0"]) {
self.currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr1"];
}else{
self.currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr2"];
self.segmenter.selectedSegmentIndex = 1;
}
self.currentViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self addChildViewController:self.currentViewController];
[self addSubview:self.currentViewController.view toView:self.containerView];
}
- (IBAction)showComponent:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0) {
UIViewController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr1"];
newViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self cycleFromViewController:self.currentViewController toViewController:newViewController];
self.currentViewController = newViewController;
} else {
UIViewController *newViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"viewControllr2"];
newViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[self cycleFromViewController:self.currentViewController toViewController:newViewController];
self.currentViewController = newViewController;
}
}
- (void)cycleFromViewController:(UIViewController*) oldViewController
toViewController:(UIViewController*) newViewController {
[oldViewController willMoveToParentViewController:nil];
[self addChildViewController:newViewController];
[self addSubview:newViewController.view toView:self.containerView];
newViewController.view.alpha = 0;
[newViewController.view layoutIfNeeded];
[UIView animateWithDuration:0.5
animations:^{
newViewController.view.alpha = 1;
oldViewController.view.alpha = 0;
}
completion:^(BOOL finished) {
[oldViewController.view removeFromSuperview];
[oldViewController removeFromParentViewController];
[newViewController didMoveToParentViewController:self];
}];
}
- (void)addSubview:(UIView *)subView toView:(UIView*)parentView {
[parentView addSubview:subView];
NSDictionary * views = #{#"subView" : subView,};
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[subView]|"
options:0
metrics:0
views:views];
[parentView addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[subView]|"
options:0
metrics:0
views:views];
[parentView addConstraints:constraints];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
I am calling loadViewFromData from another view controller and changing the appD.defults value to "index1" but its not redirecting
If I am trying to select the second segment via code i.e., calling externally through selectedSegmentIndex, it is not functioning and not getting re-directed.
Manually if I click and select a segment it is functioning properly.

trouble occurred When I pushViewController

Recently, a strange question occurred when I pushViewController to the next viewController.
Why I think it's a strange question? because it don't always appears(The probability of occurrence is low). when it appears, next viewController only shows its nav bar on screen, I still can see the rootViewController, but touching it without reaction(PopGesture is effective).Hoping for your help, thanks very much.
#pragram mark - method of pushing
- (void)clickToAccout {
if (![self countTotalSelectedNumber]) {
[SVProgressHUD showInfoWithStatus:#"没有被选择的商品"];
return;
}
CSCreatOrderViewController *creatOrderVC = [[CSCreatOrderViewController alloc] init];
creatOrderVC.totalPrice = [self countTotalPrice];
creatOrderVC.goods = [self selectedGoods];
[self.navigationController pushViewController:creatOrderVC animated:YES];
}
#pragma mark - chlid class of navgationController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationBar.tintColor = [UIColor whiteColor];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return _barStyle;
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.viewControllers.count > 0) {
viewController.hidesBottomBarWhenPushed = YES;
[SVProgressHUD dismiss];
}
[super pushViewController:viewController animated:animated];
}
- (UIViewController *)popViewControllerAnimated:(BOOL)animated {
[SVProgressHUD dismiss];
return [super popViewControllerAnimated:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - tabBarController
- (void)viewDidLoad {
[super viewDidLoad];
CSTabBar *tabBar = [[CSTabBar alloc] init];
[self setValue:tabBar forKey:#"tabBar"];
[self.tabBar setTintColor:[UIColor cz_colorWithHex:0Xec5151]];
[self addChildViewControllerWithTitle:#"首页" imageName:#"home" controllerName:#"CSHomeViewController"];
[self addChildViewControllerWithTitle:#"分类" imageName:#"classify" controllerName:#"CSClassifyViewController"];
[self addChildViewControllerWithTitle:#"查询" imageName:#"search" controllerName:#"CSSearchViewController"];
[self addChildViewControllerWithTitle:#"购物车" imageName:#"cart" controllerName:#"CSShoppingCartViewController"];
[self addChildViewControllerWithTitle:#"我的" imageName:#"mine" controllerName:#"CSMineViewController"];
self.selectedIndex = 0;
}
- (void)addChildViewControllerWithTitle:(NSString *)title imageName:(NSString *)imageName controllerName:(NSString *)controllerName {
Class cls = NSClassFromString(controllerName);
UIViewController *vc = [[cls alloc] init];
vc.title = title;
[vc.tabBarItem setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#",imageName]]];
[vc.tabBarItem setSelectedImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#_selected",imageName]]];
vc.tabBarItem.title = title;
CSNavigationController *nav = [[CSNavigationController alloc] initWithRootViewController:vc];
[self addChildViewController:nav];
}
#pragma mark - base viewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self setupNavItem];
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
_indciatorView = [[CSIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
UIWindow *keyW = [UIApplication sharedApplication].keyWindow;
[keyW addSubview:_indciatorView];
[_indciatorView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(keyW);
}];
}
- (void)setupNavItem {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
button.imageEdgeInsets = UIEdgeInsetsMake(9, 0, 9, 29);
[button setImage:[UIImage imageNamed:#"left"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(clickToDismiss) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
- (void)clickToDismiss {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
I think you should change
[super pushViewController:viewController animated:animated];
to
[self.navigationController pushViewController:viewController animated:animated];
And the same when pop
[super popViewControllerAnimated:animated];
to
[self.navigationController popViewControllerAnimated:animated];
I clear the cache of Xcode, this case don't appear. Maybe I Imported a third lib ago caused this case. But like what I asked ,it don't always appears(The probability of occurrence is low). So, hoping it has been well.

How to dismis Viewcontroller (popup) by pressing button inside my popup viewcontroller and also touch any where outside of viewcontroller?

I have one viewcontroler with one button.When i press that one pop up viewcontroller will show up.And when i touch anywhere outside it dismiss the viewcontroller .And return to my main viewcontroller.
Note
I used my popup through one viewcontroller and i use identifier name .Then i show pop up using that storyboard identifier and declared in my viewcontroller.m in btnSelectDatePressed
Needed
in that pop up view controller i have one button when user press also it should dismiss the viewcontroller and should return to my main viewcontroller.My example image is like this sample image
This is my viewcontroller.m file
#import "ViewController.h"
#import "UIViewController+ENPopUp.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)btnSelectDatePressed:(id)sender
{
UIViewController *vc = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"PopUp"];
vc.view.frame = CGRectMake(0, 0, 309.0f, 531.0f);
[self presentPopUpViewController:vc];
}
This is my popup method declared in #import "UIViewController+ENPopUp.h"
#import <UIKit/UIKit.h>
#interface UIViewController (ENPopUp)
#property (nonatomic, retain) UIViewController *en_popupViewController;
- (void)presentPopUpViewController:(UIViewController *)popupViewController;
- (void)presentPopUpViewController:(UIViewController *)popupViewController completion:(void (^)(void))completionBlock;
- (void)dismissPopUpViewController;
- (void)dismissPopUpViewControllerWithcompletion:(void (^)(void))completionBlock;
//- (IBAction)disMe:(id)sender;
#end
This is my popup method declared in `#import "UIViewController+ENPopUp.m"`
#import "UIViewController+ENPopUp.h"
#import "JWBlurView.h"
#import <objc/runtime.h>
static void * ENPopupViewControllerPropertyKey = &ENPopupViewControllerPropertyKey;
static CGFloat const kAnimationDuration = .4f;
static CGFloat const kRotationAngle = 70.f;
static NSInteger const kENPopUpOverlayViewTag = 351301;
static NSInteger const kENPopUpViewTag = 351302;
static NSInteger const kENPopUpBluredViewTag = 351303;
#implementation UIViewController (ENPopUp)
#pragma mark - Public Methods
- (void)presentPopUpViewController:(UIViewController *)popupViewController
{
[self presentPopUpViewController:popupViewController completion:nil];
}
- (void)presentPopUpViewController:(UIViewController *)popupViewController completion:(void (^)(void))completionBlock
{
self.en_popupViewController = popupViewController;
[self presentPopUpView:popupViewController.view completion:completionBlock];
}
- (void)dismissPopUpViewController
{
[self dismissPopUpViewControllerWithcompletion:nil];
}
- (void)dismissPopUpViewControllerWithcompletion:(void (^)(void))completionBlock
{
UIView *sourceView = [self topView];
JWBlurView *blurView = (JWBlurView *)[sourceView viewWithTag:kENPopUpBluredViewTag];
UIView *popupView = [sourceView viewWithTag:kENPopUpViewTag];
UIView *overlayView = [sourceView viewWithTag:kENPopUpOverlayViewTag];
[self performDismissAnimationInSourceView:sourceView withBlurView:blurView popupView:popupView overlayView:overlayView completion:completionBlock];
}
//- (IBAction)disMe:(id)sender {
// UIViewController *vc = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"Pop"];
// [self dismissViewControllerAnimated:YES completion:Nil];
//}
#pragma mark - Getters & Setters
- (UIViewController *)en_popupViewController
{
return objc_getAssociatedObject(self, ENPopupViewControllerPropertyKey);
}
- (void)setEn_popupViewController:(UIViewController *)en_popupViewController
{
objc_setAssociatedObject(self, ENPopupViewControllerPropertyKey, en_popupViewController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark - View Handling
- (void)presentPopUpView:(UIView *)popUpView completion:(void (^)(void))completionBlock
{
UIView *sourceView = [self topView];
// Check if source view controller is not in destination
if ([sourceView.subviews containsObject:popUpView]) return;
// Add overlay
UIView *overlayView = [[UIView alloc] initWithFrame:sourceView.bounds];
overlayView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
overlayView.tag = kENPopUpOverlayViewTag;
overlayView.backgroundColor = [UIColor clearColor];
// Add Blured View
JWBlurView *bluredView = [[JWBlurView alloc] initWithFrame:overlayView.bounds];
bluredView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
bluredView.tag = kENPopUpBluredViewTag;
[bluredView setBlurAlpha:.0f];
[bluredView setAlpha:.0f];
[bluredView setBlurColor:[UIColor clearColor]];
bluredView.backgroundColor = [UIColor clearColor];
[overlayView addSubview:bluredView];
// Make the background clickable
UIButton * dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
dismissButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
dismissButton.backgroundColor = [UIColor clearColor];
dismissButton.frame = sourceView.bounds;
[overlayView addSubview:dismissButton];
[dismissButton addTarget:self action:#selector(dismissPopUpViewController)
forControlEvents:UIControlEventTouchUpInside];
// Customize popUpView
popUpView.layer.cornerRadius = 3.5f;
popUpView.layer.masksToBounds = YES;
popUpView.layer.zPosition = 99;
popUpView.tag = kENPopUpViewTag;
popUpView.center = overlayView.center;
[popUpView setNeedsLayout];
[popUpView setNeedsDisplay];
[overlayView addSubview:popUpView];
[sourceView addSubview:overlayView];
[self setAnimationStateFrom:popUpView];
[self performAppearAnimationWithBlurView:bluredView popupView:popUpView completion:completionBlock];
}
#pragma mark - Animation
- (void)setAnimationStateFrom:(UIView *)view
{
CALayer *layer = view.layer;
layer.transform = [self transform3d];
}
- (CATransform3D)transform3d
{
CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DTranslate(transform, 0, 200.f, 0);
transform.m34 = 1.0/800.0;
transform = CATransform3DRotate(transform, kRotationAngle*M_PI/180.f, 1.f, .0f, .0f);
CATransform3D scale = CATransform3DMakeScale(.7f, .7f, .7f);
return CATransform3DConcat(transform, scale);
}
- (void)performAppearAnimationWithBlurView:(JWBlurView *)blurView popupView:(UIView *)popupView completion:(void (^)(void))completionBlock
{
CATransform3D transform;
transform = CATransform3DIdentity;
[UIView animateWithDuration:kAnimationDuration
animations:^ {
[self.en_popupViewController viewWillAppear:NO];
[blurView setAlpha:1.f];
popupView.layer.transform = transform;
}
completion:^(BOOL finished) {
[self.en_popupViewController viewDidAppear:NO];
if (completionBlock != nil) {
completionBlock();
}
}];
}
- (void)performDismissAnimationInSourceView:(UIView *)sourceView
withBlurView:(JWBlurView *)blurView
popupView:(UIView *)popupView
overlayView:(UIView *)overlayView
completion:(void (^)(void))completionBlock
{
CATransform3D transform = [self transform3d];
[UIView animateWithDuration:kAnimationDuration
animations:^ {
[self.en_popupViewController viewWillDisappear:NO];
[blurView setAlpha:0.f];
popupView.layer.transform = transform;
}
completion:^(BOOL finished) {
[popupView removeFromSuperview];
[blurView removeFromSuperview];
[overlayView removeFromSuperview];
[self.en_popupViewController viewDidDisappear:NO];
self.en_popupViewController = nil;
if (completionBlock != nil) {
completionBlock();
}
}];
}
#pragma mark - Getters
- (UIView*)topView {
UIViewController *recentView = self;
while (recentView.parentViewController != nil) {
recentView = recentView.parentViewController;
}
return recentView.view;
}
#end
I am beginner in ios.Some one please give some solution for my problem.Thanks in advance !
I changed the code of UIViewController+ENPopUp.m for have a visible button.
In code existe a button with screen size for dismiss view. I changed this button and now he is visible.
In presentPopUpView UIViewController+ENPopUp.m where have this comment " // Make the background clickable" I change the code to this:
CGFloat buttonSize = 10;
UIButton * dismissButton = [[UIButton alloc] init];
dismissButton.backgroundColor = [UIColor redColor];
dismissButton.frame = CGRectMake((self.view.frame.size.width/2) - (buttonSize/2),(self.view.frame.size.height/2) + (self.view.frame.size.height/4) , buttonSize, buttonSize);
[overlayView addSubview:dismissButton];
[dismissButton addTarget:self action:#selector(dismissPopUpViewController)
forControlEvents:UIControlEventTouchUpInside];
This create a red button 10x10 like in figure:
Now, you can change the color and the size of button for what you want.
I hope this can help you.

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

setFrame won't do anything

I have a problem with an app that won't set frames outside -init and -viewWillLayoutSubviews methods. What should happen when one taps the editButton is an animation that will hide the editor view. Nonetheless, nothing happens as I test it. The problem doesn't come from the animation method since the -setFrame method as it - not included in the block - doesn't work neither.
Here is the code :
-(id)init {
if (self = [super init]) {
editButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editButtonTapped)];
doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneButtonTapped)];
editor = [[UIView alloc] init];
[editor setBackgroundColor:[UIColor yellowColor]];
editor.clipsToBounds = YES;
editorIsOpen = YES;
portraitRegularModeEditorRect = CGRectMake(15, 59, 738, 100);
portraitClosedEditorEditorRect = CGRectMake(15, 59, 738, 0);
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[[self view] addSubview:editor];
[[self view] setBackgroundColor:[UIColor blueColor]];
}
-(void)viewDidAppear:(BOOL)animated {
[self setForRegularMode];
}
-(void)viewWillLayoutSubviews {
UIInterfaceOrientation io = [[UIApplication sharedApplication] statusBarOrientation];
if (io == UIInterfaceOrientationPortrait || io == UIInterfaceOrientationPortraitUpsideDown) {
//portrait
[editor setFrame:portraitRegularModeEditorRect];
} else {
//landscape
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)editButtonTapped {
[self setForScenarioLinesEditingMode];
}
-(void)doneButtonTapped {
[self setForRegularMode];
}
-(void)setForRegularMode {
editingMode = CPRegularMode;
if (!editorIsOpen) {
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationCurveEaseOut animations:^(void){
[editor setFrame:portraitRegularModeEditorRect];
} completion:^(BOOL finished) {
editorIsOpen = YES;
}];
}
[[self navigationItem] setRightBarButtonItems:[[NSArray alloc] initWithObjects:editButton,nil]];
}
-(void)setForScenarioLinesEditingMode {
editingMode = CPScenarioLinesEditingMode;
if (editorIsOpen) {
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
[editor setFrame:portraitClosedEditorEditorRect];
} completion:^(BOOL finished) {
editorIsOpen = NO;
}];
}
[[self navigationItem] setRightBarButtonItems:[[NSArray alloc] initWithObjects:doneButton,nil]];
}
If anyone can help, thanks in advance ;)
I think that the problem in your case is the fact that in -(void)viewWillLayoutSubviews method you set, lets say the default frame of your view, if you try to change the frame in other methods after the setFrame is called on your view, the -(void)viewWillLayoutSubviews will also be called and the frame of the view will be the default one. Try to remove the setFrame from your -(void)viewWillLayoutSubviews.
Is your view controller set up in storyboards, and are you using Autolayout (which is on by default?) If so, setFrame won't work and you need to edit constraints after creating outlets to them from the storyboard.
Alternatively, you can turn off Autolayout in your storyboard, as shown here.

Resources