애니메이션으로 UIView 숨김/표시
저의 단순한 목표는 애니메이션 숨김과 표시 기능을 페이드하는 것입니다.
Button.hidden = YES;
간단해.하지만 그냥 사라지지 않고 사라지게 할 수 있을까요?그런 식으로 보면 프로답지 않아 보여요.
iOS 4 이후에는 QuartzCore를 Import할 필요 없이 UIView 전환 방식만으로 이를 수행할 수 있는 방법이 있습니다.이렇게 말할 수 있습니다.
목표 C
[UIView transitionWithView:button
duration:0.4
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
button.hidden = YES;
}
completion:NULL];
재빠르다
UIView.transition(with: button, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
self.button.isHidden = false
})
이전 솔루션
마이클의 해결책은 먹히겠지만 그게 최선의 방법은 아니야
알파 페이딩의 문제는 서로 다른 겹치는 뷰 레이어가 페이드아웃될 때 이상하게 보일 수 있다는 것입니다.코어 애니메이션을 사용하는 다른 방법이 있습니다.하고 QuartzCore를 추가합니다.#import <QuartzCore/QuartzCore.h>
를 참조해 주세요.을 사용하다
- 설정하다
button.layer.shouldRasterize = YES;
경계에 수 이렇게 하면 레이어가 이상하게 섞이는 것을 막을 수 있지만 약간의 성능 저하가 있고, 픽셀 경계에 정확히 정렬되지 않으면 버튼이 흐릿하게 보일 수 있습니다.
대체 방법:
대신 다음 코드를 사용하여 페이드 애니메이션을 실행하십시오.
CAT 트랜지션 *catransition = [CAT 트랜지션 애니메이션]; 애니메이션.= kCATtransitionFade; animation.layer = 0.4; [button.layer addAnimation:Animation forKey:nil];
button.hidden = YES;
이 접근법의 장점은 버튼이 애니메이션이 되지 않더라도(버튼의 텍스트나 이미지 등) 버튼의 속성을 크로스페이딩할 수 있다는 것입니다.이행을 설정하고 나서 곧바로 속성을 설정할 수 있습니다.
UIView 애니메이션 속성은 다음과 같습니다.
- frame
- bounds
- center
- transform
- alpha
- backgroundColor
- contentStretch
설명: 애니메이션
isHidden
은 다음과 같다
Swift 4:
func setView(view: UIView, hidden: Bool) {
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.isHidden = hidden
})
}
목표 C:
- (void)setView:(UIView*)view hidden:(BOOL)hidden {
[UIView transitionWithView:view duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^(void){
[view setHidden:hidden];
} completion:nil];
}
페이드 아웃 하려면:
목표-C
[UIView animateWithDuration:0.3 animations:^{
button.alpha = 0;
} completion: ^(BOOL finished) {//creates a variable (BOOL) called "finished" that is set to *YES* when animation IS completed.
button.hidden = finished;//if animation is finished ("finished" == *YES*), then hidden = "finished" ... (aka hidden = *YES*)
}];
스위프트 2
UIView.animateWithDuration(0.3, animations: {
button.alpha = 0
}) { (finished) in
button.hidden = finished
}
스위프트 3, 4, 5
UIView.animate(withDuration: 0.3, animations: {
button.alpha = 0
}) { (finished) in
button.isHidden = finished
}
페이드인 하려면:
목표-C
button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:0.3 animations:^{
button.alpha = 1;
}];
스위프트 2
button.alpha = 0
button.hidden = false
UIView.animateWithDuration(0.3) {
button.alpha = 1
}
스위프트 3, 4, 5
button.alpha = 0
button.isHidden = false
UIView.animate(withDuration: 0.3) {
button.alpha = 1
}
이 작은 Swift 3 확장자를 사용합니다.
extension UIView {
func fadeIn(duration: TimeInterval = 0.5,
delay: TimeInterval = 0.0,
completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
UIView.animate(withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5,
delay: TimeInterval = 0.0,
completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
UIView.animate(withDuration: duration,
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.alpha = 0.0
}, completion: completion)
}
}
부드러운 페이드아웃 및 페이드인 효과를 위해 이 솔루션을 사용합니다.
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.isHidden = true
self.alpha = 0.0
}, completion: completion)
}
}
용도는 다음과 같다
uielement.fadeIn()
uielement.fadeOut()
감사해요.
스위프트 3
func appearView() {
self.myView.alpha = 0
self.myView.isHidden = false
UIView.animate(withDuration: 0.9, animations: {
self.myView.alpha = 1
}, completion: {
finished in
self.myView.isHidden = false
})
}
신속한 4.2
내선번호:
extension UIView {
func hideWithAnimation(hidden: Bool) {
UIView.transition(with: self, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.isHidden = hidden
})
}
}
간단한 방법:
func setView(view: UIView, hidden: Bool) {
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.isHidden = hidden
})
}
약간의 변경 후 @Umair Afzal이 빠르게 동작하는 코드
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
사용하기 위해서
yourView.fadeOut()
yourView.fadeIn()
가 카테고리를 요.UIView
다른 개념의 을 구현했습니다.visibility
의 가장 큰 할 수 [view setVisible:NO animated:YES]
에 동기 합니다.[view visible]
을 사용법이것은 매우 간단하지만 매우 유용합니다.
또한, "부울 논리"를 사용하는 것을 피할 수 있습니다(자세한 내용은 코드 완성, 페이지 269, 양의 부울 변수 이름 사용 참조).
재빠르다
UIView+Visibility.swift
import UIKit
private let UIViewVisibilityShowAnimationKey = "UIViewVisibilityShowAnimationKey"
private let UIViewVisibilityHideAnimationKey = "UIViewVisibilityHideAnimationKey"
private class UIViewAnimationDelegate: NSObject {
weak var view: UIView?
dynamic override func animationDidStop(animation: CAAnimation, finished: Bool) {
guard let view = self.view where finished else {
return
}
view.hidden = !view.visible
view.removeVisibilityAnimations()
}
}
extension UIView {
private func removeVisibilityAnimations() {
self.layer.removeAnimationForKey(UIViewVisibilityShowAnimationKey)
self.layer.removeAnimationForKey(UIViewVisibilityHideAnimationKey)
}
var visible: Bool {
get {
return !self.hidden && self.layer.animationForKey(UIViewVisibilityHideAnimationKey) == nil
}
set {
let visible = newValue
guard self.visible != visible else {
return
}
let animated = UIView.areAnimationsEnabled()
self.removeVisibilityAnimations()
guard animated else {
self.hidden = !visible
return
}
self.hidden = false
let delegate = UIViewAnimationDelegate()
delegate.view = self
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = visible ? 0.0 : 1.0
animation.toValue = visible ? 1.0 : 0.0
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
animation.delegate = delegate
self.layer.addAnimation(animation, forKey: visible ? UIViewVisibilityShowAnimationKey : UIViewVisibilityHideAnimationKey)
}
}
func setVisible(visible: Bool, animated: Bool) {
let wereAnimationsEnabled = UIView.areAnimationsEnabled()
if wereAnimationsEnabled != animated {
UIView.setAnimationsEnabled(animated)
defer { UIView.setAnimationsEnabled(!animated) }
}
self.visible = visible
}
}
목표-C
UIView+Visibility.h
#import <UIKit/UIKit.h>
@interface UIView (Visibility)
- (BOOL)visible;
- (void)setVisible:(BOOL)visible;
- (void)setVisible:(BOOL)visible animated:(BOOL)animated;
@end
UIView+Visibility.m
#import "UIView+Visibility.h"
NSString *const UIViewVisibilityAnimationKeyShow = @"UIViewVisibilityAnimationKeyShow";
NSString *const UIViewVisibilityAnimationKeyHide = @"UIViewVisibilityAnimationKeyHide";
@implementation UIView (Visibility)
- (BOOL)visible
{
if (self.hidden || [self.layer animationForKey:UIViewVisibilityAnimationKeyHide]) {
return NO;
}
return YES;
}
- (void)setVisible:(BOOL)visible
{
[self setVisible:visible animated:NO];
}
- (void)setVisible:(BOOL)visible animated:(BOOL)animated
{
if (self.visible == visible) {
return;
}
[self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyShow];
[self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyHide];
if (!animated) {
self.alpha = 1.f;
self.hidden = !visible;
return;
}
self.hidden = NO;
CGFloat fromAlpha = visible ? 0.f : 1.f;
CGFloat toAlpha = visible ? 1.f : 0.f;
NSString *animationKey = visible ? UIViewVisibilityAnimationKeyShow : UIViewVisibilityAnimationKeyHide;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 0.25;
animation.fromValue = @(fromAlpha);
animation.toValue = @(toAlpha);
animation.delegate = self;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:animation forKey:animationKey];
}
#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)finished
{
if ([[self.layer animationForKey:UIViewVisibilityAnimationKeyHide] isEqual:animation]) {
self.hidden = YES;
}
}
@end
Swift 5.0, 범용 기능 탑재:
func hideViewWithAnimation<T: UIView>(shouldHidden: Bool, objView: T) {
if shouldHidden == true {
UIView.animate(withDuration: 0.3, animations: {
objView.alpha = 0
}) { (finished) in
objView.isHidden = shouldHidden
}
} else {
objView.alpha = 0
objView.isHidden = shouldHidden
UIView.animate(withDuration: 0.3) {
objView.alpha = 1
}
}
}
용도:
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabelBGView)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountLabel)
hideViewWithAnimation(shouldHidden: shouldHidden, objView: itemCountButton)
서 ★★★★itemCountLabelBGView
는 입니다.UIView
,itemCountLabel
는 입니다.UILabel
&itemCountButton
는 입니다.UIButton
가 라라음음음음음음음음음음음음음음음음 is is is is is is is is is is is is whose whose whose whose whose whose whose음 is is is whose whose whose whose whose 가 있는 모든 뷰 UIView
.
스위프트 4
extension UIView {
func fadeIn(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in }) {
self.alpha = 0.0
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.isHidden = false
self.alpha = 1.0
}, completion: completion)
}
func fadeOut(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in }) {
self.alpha = 1.0
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}) { (completed) in
self.isHidden = true
completion(true)
}
}
}
또한 이 기능을 사용하려면 다음과 같은 함수를 호출하면 됩니다.
yourView.fadeOut() // this will hide your view with animation
yourView.fadeIn() /// this will show your view with animation
isHidden
을 줄 수 이하여 뷰를 수 . 알파를 사용하다
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.alpha = 0
})
그리고 표시:
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
view.alpha = 1
})
func flipViews(fromView: UIView, toView: UIView) {
toView.frame.origin.y = 0
self.view.isUserInteractionEnabled = false
UIView.transition(from: fromView, to: toView, duration: 0.5, options: .transitionFlipFromLeft, completion: { finished in
fromView.frame.origin.y = -900
self.view.isUserInteractionEnabled = true
})
}
이거 드셔보세요.
func showView(objView:UIView){
objView.alpha = 0.0
UIView.animate(withDuration: 0.5, animations: {
objView.alpha = 0.0
}, completion: { (completeFadein: Bool) -> Void in
objView.alpha = 1.0
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
objView.layer.add(transition, forKey: nil)
})
}
func HideView(objView:UIView){
UIView.animate(withDuration: 0.5, animations: {
objView.alpha = 1.0
}, completion: { (completeFadein: Bool) -> Void in
objView.alpha = 0.0
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
objView.layer.add(transition, forKey: nil)
})
}
그리고 보기 이름을 전달합니다.
showView(objView: self.viewSaveCard)
HideView(objView: self.viewSaveCard)
뷰가 디폴트로 숨김으로 설정되어 있거나 대부분의 경우 숨김 상태로 변경되어 있는 경우, 이 페이지의 어느 접근법도 FadeIn/FadeOut 애니메이션을 제공하지 않으며, 이러한 상태 중 하나만 애니메이션화됩니다. 그 이유는 UIView를 호출하기 전에 숨김 상태를 false로 설정하고 있기 때문입니다.애니메이션 방식으로 인해 갑자기 표시되며 알파만 애니메이션을 수행하면 개체 공간은 그대로 있지만 표시되지 않으므로 UI 문제가 발생합니다.
따라서 가장 좋은 방법은 뷰가 숨겨져 있는지 먼저 확인한 후 알파를 0.0으로 설정하는 것입니다. 이렇게 숨겨진 상태를 false로 설정하면 갑자기 표시되지 않습니다.
func hideViewWithFade(_ view: UIView) {
if view.isHidden {
view.alpha = 0.0
}
view.isHidden = false
UIView.animate(withDuration: 0.3, delay: 0.0, options: .transitionCrossDissolve, animations: {
view.alpha = view.alpha == 1.0 ? 0.0 : 1.0
}, completion: { _ in
view.isHidden = !Bool(truncating: view.alpha as NSNumber)
})
}
UIView.transition(with:) 기능은 멋지고 깔끔합니다.
많은 사람들이 게시했지만 아무도 거짓말이 있다는 것을 알아채지 못했습니다. 오류를 실행해야만 오류가 나타납니다.
숨겨진 속성을 true로 완벽하게 전환할 수 있지만 false로 전환하려고 하면 애니메이션 없이 보기가 갑자기 사라집니다.
이는 이 api가 뷰 내에서만 작동하기 때문입니다. 즉, 뷰 전환 시 해당 컨텐츠만 즉시 애니메이션으로 표시됩니다.
이 보기를 숨기려고 하면 바로 숨깁니다. 그러면 애니메이션 콘텐츠의 의미가 없어집니다.
이 문제를 해결하려면 뷰를 숨길 때 전환 대상이 숨길 뷰 대신 상위 뷰여야 합니다.
func transitionView(_ view: UIView?, show: Bool, completion: BoolFunc? = nil) {
guard let view = view, view.isHidden == show, let parent = view.superview else { return }
let target: UIView = show ? view : parent
UIView.transition(with: target, duration: 0.4, options: [.transitionCrossDissolve], animations: {
view.isHidden = !show
}, completion: completion)
}
UIView.transition(with: title3Label, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
self.title3Label.isHidden = !self.title3Label.isHidden
})
약간의 지연이 있는 View에 전환을 적용하면 숨김 및 표시 효과가 있음
Animatics 라이브러리를 사용하여 매우 쉽게 수행할 수 있습니다.
//To hide button:
AlphaAnimator(0) ~> button
//to show button
AlphaAnimator(1) ~> button
Swift 3의 솔루션그래서 올바른 순서로 보기를 숨기거나 숨김 해제하는 기능을 만들었습니다(숨길 경우 알파를 0으로 설정한 다음 참으로 숨김, 숨김 해제: 먼저 보기를 표시한 다음 알파를 1로 설정).
func hide(_ hide: Bool) {
let animations = hide ? { self.alpha = 0 } :
{ self.isHidden = false }
let completion: (Bool) -> Void = hide ? { _ in self.isHidden = true } :
{ _ in UIView.animate(withDuration: duration, animations: { self.alpha = 1 }) }
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
Swift 4로의 이행
UIView.transition(with: view, duration: 3, options: .transitionCurlDown,
animations: {
// Animations
view.isHidden = hidden
},
completion: { finished in
// Compeleted
})
오래된 swift 버전에 대해 접근 방식을 사용하면 다음과 같은 오류가 발생합니다.
Cannot convert value of type '(_) -> ()' to expected argument type '(() -> Void)?'
참고 자료입니다.
이 코드는 uinavigation Controller에서 viewController를 푸시하는 것과 같은 애니메이션을 제공합니다.
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromRight;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = true;
팝 애니메이션에 사용...
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromLeft;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = false;
종료된 답변 중 몇 가지를 시험해 보았습니다.어떤 답변은 한 가지 상황에서만 동작하고, 어떤 답변은 두 가지 기능을 추가해야 합니다.
옵션 1
와는 관계 없음view.isHidden
.
extension UIView {
func animate(fadeIn: Bool, withDuration: TimeInterval = 1.0) {
UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
self.alpha = fadeIn ? 1.0 : 0.0
})
}
}
그럼 패스isFadeIn
(true
또는false
)
view.animate(fadeIn: isFadeIn)
옵션 2
매개 변수를 전달하지 마십시오.에 따라 퇴색하거나 퇴색한다.isUserInteractionEnabled
이것 또한 앞뒤로 움직이는 상황에 매우 잘 맞습니다.
func animateFadeInOut(withDuration: TimeInterval = 1.0) {
self.isUserInteractionEnabled = !self.isUserInteractionEnabled
UIView.animate(withDuration: withDuration, delay: 0.0, options: .curveEaseInOut, animations: {
self.alpha = self.isUserInteractionEnabled ? 1.0 : 0.0
})
}
그럼 네가 전화해라
yourView.animateFadeInOut()
왜죠
self.isUserInteractionEnabled
?교환을 시도했다.
self.isUserInteractionEnabled
타고self.isHidden
전혀 운이 없어요.
바로 그겁니다.나도 한번 해 봐, 누군가 도움이 되길 바라.
언급URL : https://stackoverflow.com/questions/9115854/uiview-hide-show-with-animation
'code' 카테고리의 다른 글
빈 텍스트 블록을 숨기는 방법 (0) | 2023.04.13 |
---|---|
WPF TreeViewHierarchicalDataTemplate - 여러 자녀 컬렉션이 있는 개체에 바인딩 (0) | 2023.04.13 |
SQL Server Express의 제한 사항 (0) | 2023.04.13 |
PowerShell: 텍스트 파일 내용 전체를 변수에 저장 (0) | 2023.04.08 |
HTML: 유효한 ID 속성 값입니까? (0) | 2023.04.08 |