presentModalViewController를 사용하여 투명 뷰를 만드는 방법
다음과 함께 모달 뷰를 표시합니다.
[self presentModalViewController:controller animated:YES];
보기가 화면 위로 이동하면 xib 파일의 설정에 따라 투명하지만, 화면을 가득 채우면 불투명해집니다.
시야를 투명하게 유지하는 방법이 있습니까?
저는 그것이 놓이고 있는 뷰가 렌더링되지 않고 오히려 모달 뷰가 불투명해지고 있다고 의심합니다.
iOS 3.2 이후에는 "꼼수" 없이 이 작업을 수행할 수 있는 방법이 있습니다. modal PresentationStyle 속성에 대한 설명서를 참조하십시오.보기 컨트롤러를 표시할 rootViewController가 있습니다.성공의 비결은 다음과 같습니다.
viewController.view.backgroundColor = [UIColor clearColor];
rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
[rootViewController presentModalViewController:viewController animated:YES];
이 메서드를 사용하면 viewController의 배경이 투명하게 표시되고 기본 rootViewController가 표시됩니다.이것은 iPad에서만 작동하는 것으로 보인다는 점에 유의하시기 바랍니다. 아래의 설명을 참조하십시오.
보기는 여전히 투명하지만 모달 컨트롤러가 스택의 맨 위에 있으면 그 뒤의 보기가 숨겨집니다(맨 위의 보기 컨트롤러의 경우와 마찬가지입니다).해결책은 직접 수동으로 뷰를 애니메이션화하는 것입니다. 그러면 백뷰 컨트롤러가 숨겨지지 않습니다('떠나지' 않을 것입니다).
이것을 작동시키기 위해 필요했던 것:
self.window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
코드를 보고 싶은 분들을 위해 투명 뷰의 컨트롤러에 추가한 내용은 다음과 같습니다.
// Add this view to superview, and slide it in from the bottom
- (void)presentWithSuperview:(UIView *)superview {
// Set initial location at bottom of superview
CGRect frame = self.view.frame;
frame.origin = CGPointMake(0.0, superview.bounds.size.height);
self.view.frame = frame;
[superview addSubview:self.view];
// Animate to new location
[UIView beginAnimations:@"presentWithSuperview" context:nil];
frame.origin = CGPointZero;
self.view.frame = frame;
[UIView commitAnimations];
}
// Method called when removeFromSuperviewWithAnimation's animation completes
- (void)animationDidStop:(NSString *)animationID
finished:(NSNumber *)finished
context:(void *)context {
if ([animationID isEqualToString:@"removeFromSuperviewWithAnimation"]) {
[self.view removeFromSuperview];
}
}
// Slide this view to bottom of superview, then remove from superview
- (void)removeFromSuperviewWithAnimation {
[UIView beginAnimations:@"removeFromSuperviewWithAnimation" context:nil];
// Set delegate and selector to remove from superview when animation completes
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
// Move this view to bottom of superview
CGRect frame = self.view.frame;
frame.origin = CGPointMake(0.0, self.view.superview.bounds.size.height);
self.view.frame = frame;
[UIView commitAnimations];
}
iOS 8에서 이를 수행하는 Apple이 승인한 방법은 modal Presentation Style을 'UIModal Presentation OverCurrentContext'로 설정하는 것입니다.
UIViewController 설명서에서:
UIModal Presentation OverCurrentContext
상위 보기 컨트롤러의 내용 위에만 내용이 표시되는 프리젠테이션 유형입니다.프리젠테이션이 끝나면 표시된 내용 아래의 보기는 보기 계층에서 제거되지 않습니다.따라서 표시된 보기 컨트롤러가 불투명한 내용으로 화면을 채우지 않으면 기본 내용이 표시됩니다.
팝업에서 뷰 컨트롤러를 표시할 때 이 표시 스타일은 전환 스타일이 UIModalTransitionStyleCoverVertical인 경우에만 지원됩니다.다른 전환 스타일을 사용하려고 하면 예외가 발생합니다.그러나 상위 보기 컨트롤러가 포포오버에 없는 경우 다른 전환 스타일(부분 컬 전환 제외)을 사용할 수 있습니다.
iOS 8.0 이상에서 사용 가능.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/
WWDC 2014의 'View Controller Advancements in iOS 8' 비디오를 자세히 살펴봅니다.
표시된 뷰 컨트롤러에 선명한 배경색을 지정해야 합니다(그렇지 않으면 불투명하게 표시됨).
또 다른 옵션이 있습니다: 모달 컨트롤러를 보여주기 전에 전체 창의 스크린샷을 캡처합니다.캡처된 이미지를 UIImageView에 삽입하고 표시하려는 컨트롤러 보기에 이미지 보기를 추가합니다.그럼 다시 보내주세요.영상 보기 위에 다른 보기(배경 검정, 알파 0.7)를 삽입합니다.모달컨트롤러를 보여주면 투명해 보입니다.방금 iOS 4.3.1을 실행하는 아이폰4에서 사용해 봤어요. 매력.
이것은 꽤 오래된 것이지만, 나는 다음과 같은 문제를 해결했습니다.아이폰에서 내비게이션 컨트롤러를 제시해야 하기 때문에 서브뷰를 추가하는 것은 실행 가능한 해결책이 아니었습니다.
그래서 내가 한 일은:
1) 보기 컨트롤러를 표시하기 전에 현재 화면의 스크린샷을 촬영합니다.
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
2) 표시할 뷰 컨트롤러를 만들고 배경을 하위 보기로 추가하여 뒤로 보냅니다.
UIViewController * presentingVC = [UIViewController new];
UIImageView * backgroundImageOfPreviousScreen = [[UIImageView alloc] initWithImage:backgroundImage];
[presentingVC.view addSubview:backgroundImageOfPreviousScreen];
[presentingVC.view sendSubviewToBack:backgroundImageOfPreviousScreen];
3) 뷰 컨트롤러를 표시하지만, 그 전에 새 뷰 컨트롤러에서 뷰 DidLoad에 투명 뷰를 추가합니다(ILTranscluentView를 사용했습니다)
-(void)viewDidLoad
{
[super viewDidLoad];
ILTranslucentView * translucentView = [[ILTranslucentView alloc] initWithFrame:self.view.frame];
[self.view addSubview:translucentView];
[self.view sendSubviewToBack:translucentView];
}
그게 다예요!
다른 질문에 이에 대한 제 소견을 적었는데, 요점은 전화를 해야 한다는 것입니다.modalPresentationStyle = UIModalPresentationCurrentContext
모든 화면을 소유하고 있는 사람들에게 말입니다.③ [UIA Application Shared Application] ④ window(윈도우) rootViewController(루트뷰컨트롤러).과는운께될다도가다hosto될euwat과odvw께운eu는w가rvetoh >modalPresentationStyle = UIModalPresentationFullScreen
.
제가 이 문제를 구체적으로 어떻게 해결했는지 궁금하시다면 제 다른 자세한 글을 읽어주세요.행운을 빕니다.
이는 IOS 8에서 고장난 것으로 보이며, 저는 내비게이션 컨트롤러를 사용하고 있으며, 표시되는 컨텍스트는 Navigation menu 컨텍스트이며, 우리의 경우 슬라이딩 메뉴 컨트롤러입니다.
'TWTSideMenuViewController' 포드를 사용하고 있는데, '0.3'은 아직 라이브러리 또는 위에서 설명한 방법의 문제인지 확인하지 못했습니다.
iOS 8-9에서는 이것이 효과가 있었습니다.
1 - 보기 컨트롤러의 배경을 알파로 설정합니다.
2- 다음 코드를 추가합니다.
TranslucentViewController *tvc = [[TranslucentViewController alloc] init];
self.providesPresentationContextTransitionStyle = YES;
self.definesPresentationContext = YES;
[tvc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
[self.navigationController presentViewController:tvc animated:YES completion:nil];
꽤 오래된 질문인거 압니다저는 이 문제로 꼼짝 못했고 이 문제를 통해 리드를 잡을 수 있었습니다.그래서 여기에 제가 어떻게 작동했는지를 적어봅니다 :) . 스토리보드를 사용하고 있고 뷰컨트롤러에 제시할 것입니다.뷰 컨트롤러의 배경색은 투명합니다.이제 segue의 Attributes inspector에서 프레젠테이션을 "Over current context"로 설정합니다.그리고 저에겐 효과가 있었습니다.저는 아이폰을 위해 개발하고 있습니다.
추가 UI 창에 모달 폼 시트를 표시하기 위해 오픈 소스 라이브러리 MZFormSheetController를 만들었습니다.투명 모드 뷰 컨트롤러를 표시하는 데 사용할 수 있으며, 표시된 뷰 컨트롤러의 크기도 조정할 수 있습니다.
내 상태에서 나는 같은 뷰컨트롤러를 보고 있습니다.UIView를 유지할 수 있는 새로운 뷰 컨트롤러를 만드십시오.알파 속성으로 설정하여 보기를 투명하게 만듭니다.그런 다음 버튼을 클릭하면 이 코드가 작성됩니다.좋아 보여요.
UIGraphicsBeginImageContext(objAppDelegate.window.frame.size);
[objAppDelegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIViewController *controllerForBlackTransparentView=[[[UIViewController alloc] init] autorelease];
[controllerForBlackTransparentView setView:viewForProfanity];
UIImageView *imageForBackgroundView=[[UIImageView alloc] initWithFrame:CGRectMake(0, -20, 320, 480)];
[imageForBackgroundView setImage:viewImage];
[viewForProfanity insertSubview:imageForBackgroundView atIndex:0];
[self.navigationController presentModalViewController:controllerForBlackTransparentView animated:YES];
그리고 제가 원하는 걸 보여줍니다.누군가에게 도움이 되길 바랍니다.
문제를 해결할 수 있는 카테고리가 여기 있습니다.
//
// UIViewController+Alerts.h
//
#import <UIKit/UIKit.h>
@interface UIViewController (Alerts)
- (void)presentAlertViewController:(UIViewController *)alertViewController animated:(BOOL)animated;
- (void)dismissAlertViewControllerAnimated:(BOOL)animated;
@end
//
// UIViewController+Alerts.m
//
#import "UIViewController+Alerts.h"
@implementation UIViewController (Alerts)
- (void)presentAlertViewController:(UIViewController *)alertViewController animated:(BOOL)animated
{
// Setup frame of alert view we're about to display to just off the bottom of the view
[alertViewController.view setFrame:CGRectMake(0, self.view.frame.size.height, alertViewController.view.frame.size.width, alertViewController.view.frame.size.height)];
// Tag this view so we can find it again later to dismiss
alertViewController.view.tag = 253;
// Add new view to our view stack
[self.view addSubview:alertViewController.view];
// animate into position
[UIView animateWithDuration:(animated ? 0.5 : 0.0) animations:^{
[alertViewController.view setFrame:CGRectMake(0, (self.view.frame.size.height - alertViewController.view.frame.size.height) / 2, alertViewController.view.frame.size.width, alertViewController.view.frame.size.height)];
}];
}
- (void)dismissAlertViewControllerAnimated:(BOOL)animated
{
UIView *alertView = nil;
// find our tagged view
for (UIView *tempView in self.view.subviews)
{
if (tempView.tag == 253)
{
alertView = tempView;
break;
}
}
if (alertView)
{
// clear tag
alertView.tag = 0;
// animate out of position
[UIView animateWithDuration:(animated ? 0.5 : 0.0) animations:^{
[alertView setFrame:CGRectMake(0, self.view.frame.size.height, alertView.frame.size.width, alertView.frame.size.height)];
}];
}
}
@end
많은 연구 끝에 이것이 우리의 문제를 해결하고 우리의 목적을 달성할 것으로 보입니다.
식별자를 사용하여 source VC에서 destination VC로 seegue를 만듭니다.
예를 들어 "GoToDestinationViewController"를 사용하면 삶을 쉽게 만들 수 있습니다. 현재 뷰 컨트롤러, 즉 투명 뷰 뒤에 원하는 것을 소스로, 목적지를 목적지로 고려해 보겠습니다.
이제 viewDidLoad: 또는 view의 source VC에 있습니다.
performSegueWithIdentifier("goToDestinationViewController", sender: nil)
반쯤 지나갔으니 다행입니다.이제 스토리보드로 이동합니다.segue를 클릭합니다.이런 모습일 거야 seegue
표시된 내용으로 옵션을 변경합니다.
이제 진짜 해결책이 나옵니다.
목적지 보기컨트롤러 보기DidLoad가 이 코드를 추가했습니다.
self.modalPresentationStyle = .Custom
.........................................................................그 쉬운 일..........................................................................................
다른 방법은 "컨테이너 뷰"를 사용하는 것입니다.1 아래에 알파를 만들고 seque로 임베딩하면 됩니다.X코드 5, iOS7을 목표로 합니다.
이미지를 보여줄 수 없습니다. 평판이 부족합니다.)
iOS6에서 볼 수 있는 컨테이너 뷰.
이 코드는 iOS6 및 iOS7에서 아이폰에서 정상적으로 작동합니다.
presentedVC.view.backgroundColor = YOUR_COLOR; // can be with 'alpha'
presentingVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[presentingVC presentViewController:presentedVC animated:YES completion:NULL];
하지만 이렇게 하면 '밑에서 미끄러지는' 애니메이션이 사라집니다.
iOS 7 이상을 위한 우아하고 간단한 솔루션을 찾았습니다!
iOS 8의 경우 애플이 UIModal Presentation OverCurrentContext를 추가했지만 iOS 7 이전 버전에서는 작동하지 않아 제 경우에는 사용할 수 없었습니다.
카테고리를 만들어 아래 코드를 넣어주세요.
.h 파일
typedef void(^DismissBlock)(void);
@interface UIViewController (Ext)
- (DismissBlock)presentController:(UIViewController *)controller
withBackgroundColor:(UIColor *)color
andAlpha:(CGFloat)alpha
presentCompletion:(void(^)(void))presentCompletion;
@end
.m파일
#import "UIViewController+Ext.h"
@implementation UIViewController (Ext)
- (DismissBlock)presentController:(UIViewController *)controller
withBackgroundColor:(UIColor *)color
andAlpha:(CGFloat)alpha
presentCompletion:(void(^)(void))presentCompletion
{
controller.modalPresentationStyle = UIModalPresentationCustom;
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
__block UIView *overlay = [[UIView alloc] initWithFrame:keyWindow.bounds];
if (color == nil) {
color = [UIColor blackColor];
}
overlay.backgroundColor = color;
overlay.alpha = alpha;
if (self.navigationController != nil) {
[self.navigationController.view addSubview:overlay];
}
else if (self.tabBarController != nil) {
[self.tabBarController.view addSubview:overlay];
}
else {
[self.view addSubview:overlay];
}
self.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentViewController:controller
animated:true
completion:presentCompletion];
DismissBlock dismissBlock = ^(void) {
[self dismissViewControllerAnimated:YES completion:nil];
[UIView animateWithDuration:0.25
animations:^{
overlay.alpha = 0;
} completion:^(BOOL finished) {
[overlay removeFromSuperview];
}];
};
return dismissBlock;
}
@end
참고: NavigationController, tabBarController에서도 작동합니다.
사용 예:
// Please, insure that your controller has clear background
ViewController *controller = [ViewController instance];
__block DismissBlock dismissBlock = [self presentController:controller
withBackgroundColor:[UIColor blackColor]
andAlpha:0.5
presentCompletion:nil];
// Supposed to be your controller's closing callback
controller.dismissed = ^(void) {
dismissBlock();
};
맛있게 드세요! 그리고 피드백을 남겨주세요.
이것이 지금까지 발견한 방법 중 가장 훌륭하고 깨끗한 방법입니다.
@protocol EditLoginDelegate <NSObject>
- (void)dissmissEditLogin;
@end
- (IBAction)showtTransparentView:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"foo bar"
delegate:self
cancelButtonTitle:@"cancel"
destructiveButtonTitle:@"destructive"
otherButtonTitles:@"ok", nil];
[actionSheet showInView:self.view];
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet{
UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
self.editLoginViewController = [loginStoryboard instantiateViewControllerWithIdentifier:@"EditLoginViewController"];
self.editLoginViewController.delegate = self;
[self.editLoginViewController viewWillAppear:NO];
[actionSheet addSubview:self.editLoginViewController.view];
[self.editLoginViewController viewDidAppear:NO];
}
내가 찾은 가장 좋은 해결책은 addChildViewController 방법을 사용하는 것입니다.좋은 예: 자식 뷰 컨트롤러의 뷰를 부모 뷰 컨트롤러의 하위 뷰에 추가합니다.
여러 방법을 사용하여 해결하려고 노력하였으나 여전히 실패하였고, 최종적으로 다음 코드가 구현되었습니다.
스위프트의 결의:
// A.swift init method
modalPresentationStyle = .currentContext // or overCurrentContent
modalTransitionStyle = .crossDissolve // dissolve means overlay
B 보기 컨트롤러에서 다음을 수행합니다.
// B.swift
let a = A()
self.present(a, animated: true, completion: nil)
언급URL : https://stackoverflow.com/questions/587681/how-to-use-presentmodalviewcontroller-to-create-a-transparent-view
'programing' 카테고리의 다른 글
Maria DB 루트가 없으면 Engine=CONNECT로 테이블을 드롭할 수 없습니다. (0) | 2023.09.11 |
---|---|
맨 위 탐색 모음 페이지의 맨 위 내용 (0) | 2023.09.11 |
왜 포인터를 켜지 않습니까? (0) | 2023.09.11 |
엔티티 프레임워크를 사용하여 Oracle DB에 쿼리할 때 오류 "ORA-00933"이 발생하는 경우가 있지만 웹 앱을 재시작하면 작동합니다. (0) | 2023.09.11 |
CSS로 이미지를 그레이아웃하시겠습니까? (0) | 2023.09.11 |