[英]UIView (without controller) : get notified when self disappears
我有一個沒有任何關聯的UIViewController的UIView,它始終使用自動布局和layoutIfNeeded進行動畫處理(請參見下面的代碼)。 但是,當該視圖(包含在另一個視圖中)消失時(例如,當模態視圖覆蓋了它所包含的視圖時),並且在我關閉了該模態視圖之后,動畫視圖不再進行動畫處理。
我設法用didMoveToWindow:animated方法對其進行了動畫處理,但是我不確定這是否是正確的方法。
@interface AnimatingView()
@property (strong, nonatomic) UIView *aSubview;
@property (strong, nonatomic) NSLayoutConstraint *constraintTop;
@property (assign, nonatomic, getter = isStarted) BOOL started;
@property (assign, nonatomic) BOOL stopAnimation;
@end
@implementation AnimatingView
- (id)init
{
self = [super init];
if (self) {
self.stopAnimation = YES;
/* setting base auto layout constraints */
}
return self;
}
-(void)animate{
float aNewConstant = arc4random_uniform(self.frame.size.height);
[UIView animateWithDuration:ANIMATION_DURATION animations:^{
[self removeConstraint:self.constraintTop];
self.constraintTop = [NSLayoutConstraint constraintWithItem:self.aSubview attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:aNewConstant];
[self addConstraint:self.constraintTop];
[self layoutIfNeeded];
} completion:^(BOOL finished) {
if (finished && !self.stopAnimation) {
[self animate];
}
}];
}
- (void)didMoveToWindow{
[super didMoveToWindow];
if ([self isStarted]) {
[self stop];
[self start];
}
}
-(void)start{
if (![self isStarted]) {
self.stopAnimation = NO;
[self setStarted:YES];
[self animate];
}
}
-(void)stop{
if ([self isStarted]) {
self.stopAnimation = YES;
[self setStarted:NO];
}
}
@end
您始終可以使用行為模式:KVO來控制UIView的狀態或我將要執行的操作,並在需要時使用通知為視圖添加動畫。 這兩個選項均有效。 您還可以擁有與此類關聯的委托,並在UIView中實現所需的行為。
假設您的視圖包含在Controller包含的另一個視圖中,則可以設置一個名為didReturnFromModalChildView
的BOOL變量,每次您顯示該模式視圖時,將其設置為true。 當您關閉該模式視圖時,您的應用程序將調用-(void)viewWillAppear:(BOOL)animated
。 在這里,您必須檢查BOOL變量是否設置為“是”,然后使用公共方法調用,如果您具有要創建動畫的視圖的引用,或者是委托過程或觀察者通知模式。 不要忘記將didReturnFromModalChildView設置為false。
我希望這能幫到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.