简单的代码实现的炫酷navigationbar

动图简单的代码实现的炫酷navigationbar

技术原理:

当你下拉scrollview的时候,会监听scrollview的contentOffset来调整头部背景图片的位置,通过CGAffineTransformMakeTranslation和CGAffineTransformScale实现头像的缩小。

具体代码实现:

-(void)willMoveToSuperview:(UIView *)newSuperview
{
[self.scrollView addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionNew) context:Nil];
self.scrollView.contentInset = UIEdgeInsetsMake(self.frame.size.height, ,, );
self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;
} -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGPoint newOffset = [change[@"new"] CGPointValue];
[self updateSubViewsWithScrollOffset:newOffset];
} -(void)updateSubViewsWithScrollOffset:(CGPoint)newOffset
{ float destinaOffset = -;
float startChangeOffset = -self.scrollView.contentInset.top;
newOffset = CGPointMake(newOffset.x, newOffset.y<startChangeOffset?startChangeOffset:(newOffset.y>destinaOffset?destinaOffset:newOffset.y)); float subviewOffset = self.frame.size.height-;
float newY = -newOffset.y-self.scrollView.contentInset.top;
float d = destinaOffset-startChangeOffset;
float alpha = -(newOffset.y-startChangeOffset)/d;
float imageReduce = -(newOffset.y-startChangeOffset)/(d*);
self.subTitleLabel.alpha = alpha;
self.titleLabel.alpha = alpha;
self.frame = CGRectMake(, newY, self.frame.size.width, self.frame.size.height);
self.backImageView.frame = CGRectMake(, -0.5*self.frame.size.height+(1.5*self.frame.size.height-)*(-alpha), self.backImageView.frame.size.width, self.backImageView.frame.size.height); CGAffineTransform t = CGAffineTransformMakeTranslation(,(subviewOffset-0.35*self.frame.size.height)*(-alpha));
_headerImageView.transform = CGAffineTransformScale(t,
imageReduce, imageReduce); self.titleLabel.frame = CGRectMake(, 0.6*self.frame.size.height+(subviewOffset-0.45*self.frame.size.height)*(-alpha), self.frame.size.width, self.frame.size.height*0.2);
self.subTitleLabel.frame = CGRectMake(, 0.75*self.frame.size.height+(subviewOffset-0.45*self.frame.size.height)*(-alpha), self.frame.size.width, self.frame.size.height*0.1);
}

Demo分享:

GitHub:https://github.com/ianisme/CoolNavi
上一篇:「杂项」NOIP 2020 - 赛后总结


下一篇:.net postsharp编译时生成的代码?