问题描述
我正在玩滚动视图,但遇到了一个我一直在纠结的问题.我在 Storyboard 中创建了一个视图控制器.视图控制器包含一个填充整个超级视图的滚动视图.
I am playing around with scroll views, and I've run into an issue I'be stuck with. I have a view controller create in Storyboard. The view controller contains a scroll view which fills the entire superview.
然后我以编程方式将图像添加到滚动视图.图像确实显示在滚动视图中,分页工作得很好.唯一的问题是滚动视图设置为填充超级视图,但保存图像的图像视图似乎停在导航栏的上方.如何让图像视图填充滚动视图中的整个视图?
I then added the images programmatically to the scroll view. The images do show within the scroll view and paging works just fine. Only problem is the scroll view is set ti fill superview but the image view that hold the images seems like it stops above where the navigation bar would be. How can I have the image view fill the whole view within the scroll view?
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pagingView: UIPageControl!
var images = [UIImage]()
var frame = CGRect(x: 0, y: 0,width: 0,height: 0)
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
scrollView.isPagingEnabled = true
images = [UIImage(named: "Slide1")!, UIImage(named: "Slide2")!, UIImage(named: "Slide3")!, UIImage(named: "Slide4")!]
pagingView.numberOfPages = images.count
// This is where I think I'm having the height problem.
for i in 0..<images.count {
let imageView = UIImageView()
let x = self.view.frame.size.width * CGFloat(i)
imageView.frame = CGRect(x: x, y: 0, width: self.view.frame.width, height: self.view.frame.height)
imageView.contentMode = .scaleAspectFill
imageView.image = images[i]
scrollView.contentSize.width = scrollView.frame.size.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
pagingView.currentPage = Int(pageNumber)
}
将导航栏设置为隐藏后,这是输出
After setting nav bar to hidden, here is the output
滚动视图背景颜色为红色
Scroll view background color is red
推荐答案
以编程方式scrollView.clipsToBounds = true
在UIStoryBoard
- 点击view->Attributes Inspector
In UIStoryBoard
- Click the view->Attributes Inspector
如果你想看到整个屏幕,一定要添加 scrollView
的 topConstraint
分配的 superView
并隐藏 viewWillAppear
中的导航栏,
If you would like to see the whole screen, make sure to add the topConstraint
of scrollView
assigned superView
and hide the navigationBar
in viewWillAppear
,
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
确保删除状态栏
Make sure to remove the status bar by
override var prefersStatusBarHidden: Bool {
return true
}
更新图像的 Y 位置.
Update the Y position of Image.
imageView.frame = CGRect(x: x, y: **self.scrollView.frame.minY**, width: self.view.frame.width, height: self.view.frame.height)
将 scrollView
topConstraint 更新为 -20.
Update the scrollView
topConstraint by -20.
这篇关于如何在滚动视图中填充图像以填充屏幕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!