问题描述
向下滚动时,如何使用 autolayout
缩放 imageView
?
How can I simply scaling imageView
with autolayout
when scrolling down ?
尝试看看视差效果但不完全是我想要的。
Try to see parallax effect but not exactly what I wanted.
我只想使用 scrollView
以及可以调整大小的标题 ImageView
取决于 scrollView
位置。
I just want to use a scrollView
and a header ImageView
who can resize depends on scrollView
position.
推荐答案
一步一步:
1 - 打开故事板并在这些约束的基础上添加图像视图(选择你的宽高比):
1 - open storyboard and add an image view on top with these constraint (choose your aspect ratio) :
2 - 选择aspectFill模式和你的uiimage的clipSubviews
2 - select aspectFill mode and clipSubviews for your uiimage
3 - 在你的viewController顶部添加一个UIScrollView,里面有一个子视图。有关使用scrollView的自动布局的所有详细信息:
3 - add a UIScrollView on top of your viewController with a child view inside. All the details about the auto layout with scrollView : http://natashatherobot.com/ios-autolayout-scrollview/
4 - 然后在您的代码中对您的imageView和scrollView进行插座引用。
4 - then make outlets reference of your imageView and scrollView in your code.
5 - 在viewDidLoad中,插入
self.automaticallyAdjustsScrollViewInsets = false并设置scrollView的contentInsets和contentOffset:
5 - in viewDidLoad, insertself.automaticallyAdjustsScrollViewInsets = false and set contentInsets and contentOffset of the scrollView :
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let imageHeight = imageView.frame.height
let newOrigin = CGPoint(x: 0, y: -imageHeight)
scrollView.contentOffset = newOrigin
scrollView.contentInset = UIEdgeInsets(top: imageHeight, left: 0, bottom: 0, right: 0)
}
}
6 - 将scrollviewDelegate添加到ViewController和scrollViewDidScroll方法以获取位置scrollView
6 - add scrollviewDelegate to the ViewController and the scrollViewDidScroll method to get position of the scrollView
class ViewController: UIViewController, UIScrollViewDelegate
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
if offsetY < 0
{
imageView.frame.size.height = -offsetY
}
else
{
imageView.frame.size.height = imageView.frame.height
}
}
7 - 然后构建并运行。
7 - then build and run.
你可以在github上下载例子:
you can download example on github:https://github.com/raphrel/scalingImageWhenScrollDown
可能有更好的解决方案,但这个有效。
享受
there is maybe a better solution but this one works.enjoy
这篇关于向下滚动时ImageView缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!