我希望我的scrollview框架与superview框架的尺寸相同。并设置contentsize,使其包含所有imageViews。
问题在于AutoLayout,宽度和高度是600 x 480,我使用的是iphone5,尺寸类是w:Compact / h:Any。(我期望类似:320 x 523)。
我的约束是:具有超视图的等宽度,具有超视图的等高(乘数0.8),水平中心X和垂直中心Y.
let pagesScrollViewSize = scrollView.frame.size
println("pagesScrollViewSize : \(pagesScrollViewSize)") //600x480
scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(pageCount), pagesScrollViewSize.height)
有人知道如何解决这个问题吗? imageview看起来比屏幕的框架大,因此.SizeAspectFit不遵循正确的尺寸。它不是滚动到另一个imageView,而是滚动查看图像的其余部分,这是我不想要的。
编辑:
这是ViewController.swift中的完整代码:
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var scrollView: UIScrollView!
var pageViews: [UIImageView?] = []
var pageImages : [UIImage?] = []
override func viewDidLoad() {
super.viewDidLoad()
pageImages = [UIImage(named:"photo1.png"),
UIImage(named:"photo2.png"),
UIImage(named:"photo3.png"),
UIImage(named:"photo4.png")]
let pageCount = pageImages.count
pageControl.currentPage = 0
pageControl.numberOfPages = pageCount
for _ in 0..<pageCount {
pageViews.append(nil)
}
let pagesScrollViewSize = scrollView.frame.size
println("pagesScrollViewSize : \(pagesScrollViewSize)")
scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(pageCount), pagesScrollViewSize.height)
loadVisiblePages()
}
//when scrolling
func scrollViewDidScroll(scrollView: UIScrollView!){
loadVisiblePages()
}
func loadVisiblePages(){
let pageWidth = scrollView.frame.size.width
let page = Int(floor( (scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth*2.0) ))
println("page: \(page)")
pageControl.currentPage = page
let firstPage = page-1
let lastPage = page+1
//remove all the pages before firstPage
for var index = 0; index < firstPage; ++index{
purgePage(index)
}
//load pages in our range
for var index = firstPage; index <= lastPage; ++index {
loadPage(index)
}
//remove after lastPage
for var index = lastPage+1; index < pageImages.count; ++index {
purgePage(index)
}
}
func loadPage(index:Int){
if index < 0 || index >= pageImages.count {
return
}
if let pageView = pageViews[index] {
//already loaded
}
else {
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(index)
frame.origin.y = 0.0
println("\(frame)")
var newImageView = UIImageView(image:pageImages[index])
newImageView.contentMode = .ScaleAspectFit
newImageView.frame = frame
scrollView.addSubview(newImageView)
pageViews[index] = newImageView
}
}
func purgePage(index:Int){
if index < 0 || index >= pageImages.count {
return
}
if let pageView = pageViews[index] {
pageView.removeFromSuperview()
pageViews[index] = nil
}
}
}
由于
答案 0 :(得分:4)
在viewDidAppear
或viewDidLayoutSubviews
之后才会应用尺寸类(或任何自动布局更改)。您需要将此代码移动到其中一个代码中。您正在查看视图的框架,因为它是从Interface Builder文档(xib或storyboard)中加载的。在这些生命周期事件之后,你永远不应该检查框架。