用了UIView分类UIViewAnimationWithBlocks里的类方法:
+ (void)transitionFromView:(UIView *)fromView //第一个view
toView:(UIView *)toView //第二个view
duration:(NSTimeInterval)duration //翻转时间
options:(UIViewAnimationOptions)options//翻转方向
completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(4_0); // toView added to fromView.superview, fromView removed from its superview
需要注意的是fromView和toView需要添加到同一个父view上,这样才会让父view翻转,不然你整个window都在翻转别怪我🤣
- (UIView *)firstView
{
if (!_firstView)
{
_firstView = [UIView new];
_firstView.frame = self.bounds;
UIImageView *imgView = [UIImageView new];
imgView.frame = _firstView.bounds;
imgView.clipsToBounds = YES;
imgView.contentMode = UIViewContentModeScaleAspectFill;
imgView.image = [UIImage imageNamed:@"car1"];
[_firstView addSubview:imgView];
UILabel *label = [UILabel new];
label.frame = CGRectMake(0, self.frame.size.height - 50, self.frame.size.width, 50);
label.backgroundColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = @"我是正面";
[_firstView addSubview:label];
[self addSubview:_firstView];
_firstView.layer.cornerRadius = 5;
_firstView.clipsToBounds = YES;
}
return _firstView;
}
- (SecondView *)secondView
{
if (!_secondView)
{
_secondView = [[SecondView alloc] initWithFrame:self.bounds];
_secondView.layer.cornerRadius = 5;
_secondView.clipsToBounds = YES;
}
return _secondView;
}
第一个view加到父view上,第二个只初始化,不添加到父view
- (void)setTitle:(NSString *)title
{
_title = title;
if ([title isEqualToString:@"反面"])
{
if (self.click)
{
self.click(@"正面");
}
[UIView transitionFromView:self.firstView toView:self.secondView duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
NSLog(@"翻转到了正面");
}];
}else
{
if (self.click)
{
self.click(@"反面");
}
[UIView transitionFromView:self.secondView toView:self.firstView duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
NSLog(@"翻转到了反面");
}];
}
}
以上。
网友评论