我试图在我的应用中实现以下功能:
当我从滚动视图的顶部向下拖动时,图像视图的高度增加,在宽高比填充模式下,给人以缩放的印象。
当我放手时,图像会恢复到原来的高度。
所以基本上,我试图复制Facebook应用程序的即时文章页面。
问题是我无法动画图像视图恢复原始大小。它似乎总是挺身而出。由于某种原因,UIView.animateWithDuration()在这里不起作用:/
这是我的代码: (imageHeight是UIImageView高度约束的IBOutlet)
func scrollViewDidScroll(scrollView: UIScrollView) {
let y = self.scrollView.contentOffset.y
if y < 0 && self.imageHeight.constant < 500
{
self.imageHeight.constant += (-1*y)*0.5;
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.stoppedScrolling()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate
{
self.stoppedScrolling()
}
}
func stoppedScrolling()
{
UIView.animateWithDuration(1) {
self.imageHeight.constant = 180
}
}
Here's a gif of the result 此外,它并没有显示在gif中,但是在结束触摸和调整大小之间有半秒的延迟
答案 0 :(得分:1)
看起来它是由UIImageView的高度约束导致的,我尝试通过代码创建UI并使用frame属性来控制它,它可以工作。
很抱歉我不知道如何编写swift代码,但我认为我可以知道你的意思,你必须也可以阅读我的代码,如下:
#import "MainViewController.h"
@interface MainViewController ()
@property UIScrollView *scrollView;
@property UIImageView *imageView;
@property bool needReceiveDraggingFlag;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
_scrollView.backgroundColor = [UIColor grayColor];
_scrollView.delegate = self;
_scrollView.scrollEnabled = YES;
_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width,_scrollView.frame.size.height*1.2f);
[self.view addSubview:_scrollView];
UILabel *lbInfo = [[UILabel alloc] initWithFrame:CGRectMake(50, 300, 200, 30)];
lbInfo.backgroundColor = [UIColor greenColor];
lbInfo.text = @"Test label";
[_scrollView addSubview:lbInfo];
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
_imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:_imageView];
_needReceiveDraggingFlag = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"scrollViewDidScroll");
if(_needReceiveDraggingFlag){
float y = _scrollView.contentOffset.y;
if (y<0 && _imageView.frame.size.width<300) {
float nowImageLength = _imageView.frame.size.width;
float targetImageLength = nowImageLength + -y*0.5f;
_imageView.frame = CGRectMake(0, 0, targetImageLength, targetImageLength);
}
}
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
NSLog(@"scrollViewDidEndDragging");
[self stoppedScrolling];
}
-(void)stoppedScrolling{
_needReceiveDraggingFlag = NO;
[UIView animateWithDuration:1 animations:^{
self.imageView.frame = CGRectMake(0, 0, 100, 100);
} completion:^(BOOL isFinished){
_needReceiveDraggingFlag = YES;
}];
}
@end
希望它可以帮到你。