問題描述
向下滾動時如何使用 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 - 為你的 uiimage 選擇 aspectFill 模式和 clipSubviews
2 - select aspectFill mode and clipSubviews for your uiimage
3 - 在 vi??ewController 的頂部添加一個 UIScrollView,里面有一個子視圖.有關使用 scrollView 的自動布局的所有詳細信息:http://natashatherobot.com/ios-autolayout-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 - 在 vi??ewDidLoad 中,插入self.automaticallyAdjustsScrollViewInsets = false 并設置 scrollView 的 contentInsets 和 contentOffset :
5 - in viewDidLoad, insert self.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 上下載示例:https://github.com/raphrel/scalingImageWhenScrollDown
you can download example on github: https://github.com/raphrel/scalingImageWhenScrollDown
也許有更好的解決方案,但這個可行.享受
there is maybe a better solution but this one works. enjoy
這篇關于向下滾動時 ImageView 縮放的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!