原创blog,转载请注明出处
http://blog.youkuaiyun.com/hello_hwc?viewmode=contents
欢迎关注我的iOS SDK详解专栏
http://blog.youkuaiyun.com/column/details/huangwenchen-ios-sdk.html
Demo效果
注:本文并没有完全实现Safari的navBar功能:比如textfield开始编辑的时候navBar恢复正常,比如监听Scrollview的速度。个人觉得,懂得如何伸缩以及控制textfile的大小颜色,其他的都不是问题。
实现过程
在ViewDidload中,设置配置textfield,这里要注意一点,一定要把textfield放到一个Containview里,否则后文的transform将不会得到想要的效果。
CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
UIView * containview = [[UIView alloc] initWithFrame:CGRectMake(0, 0,screenWidth - 30, 30)];
self.navTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 0,screenWidth - 30, 30)];
self.navTextfield.borderStyle = UITextBorderStyleNone;
self.navTextfield.textAlignment = NSTextAlignmentCenter;
self.navTextfield.backgroundColor = [self lightGrayWithAplpa:1.0];
self.navTextfield.layer.cornerRadius = 5.0;
self.navTextfield.layer.masksToBounds = true;
[containview addSubview:self.navTextfield];
self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
self.navigationItem.titleView = containview;
//设定初始值
self.navTextfield.text = @"www.baidu.com";
在scrollViewDidScroll中,通过Offset,来动态的改变颜色和Transform
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat offsetY = scrollView.contentOffset.y;
//定义,移动40距离的时候,缩小到最小
CGFloat progress;
if (offsetY > -64) {
progress = (offsetY + 64)/40;
progress = MIN(progress, 1);
}else{
progress = 0;
}
//处理Scale与Alpha
CGFloat scale = 1 - 0.4*progress;
CGFloat alpha = 1 - progress;
self.navTextfield.backgroundColor = [self lightGrayWithAplpa:alpha];
//计算要位移的距离
CGFloat navHeight = 44;
CGFloat navOffSetY = -1 * navHeight * 0.4 * progress;
CGFloat textFieldOffsetY = navHeight * 0.2 * progress;
CGAffineTransform scaleTran = CGAffineTransformMakeScale(scale, scale);
CGAffineTransform transTran = CGAffineTransformMakeTranslation(0, textFieldOffsetY);
self.navTextfield.transform = CGAffineTransformConcat(scaleTran, transTran);
self.navigationController.navigationBar.transform = CGAffineTransformMakeTranslation(0,navOffSetY);
}
这里的颜色函数为这个
-(UIColor *)lightGrayWithAplpa:(CGFloat)alpha{
return [UIColor colorWithRed:225.0/255 green:225.0/255 blue:225.0/255 alpha:alpha];
}
本文详细介绍了如何在iOS应用中实现动态效果,包括在ScrollView滚动时改变UI元素的颜色和位置,通过设置TextField和navigationBar的样式和响应滚动事件来达到自适应布局的目的。
1万+

被折叠的 条评论
为什么被折叠?



