UITcrollView在UITableView单元格中的问题

时间:2015-04-20 20:27:18

标签: ios uitableview swift uiscrollview

我一直在尝试向表格视图的单元格添加滚动视图,但一直在遇到缺少图像的问题。滚动视图中的页面似乎正在正确加载(基于调试视图层次结构),但没有显示任何图像。

这是我的代码:

class AppImagesTableViewCell: UITableViewCell, UIScrollViewDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var label: UILabel!

var pageViews: [UIImageView?] = []
var sixPlusImages: [UIImage?] = []

override func awakeFromNib() {
    super.awakeFromNib()

    sixPlusImages = [
        UIImage(named: "Glance 5.5.png"),
        UIImage(named: "Currencies 5.5.png"),
        UIImage(named: "Swipe 5.5.png"),
        UIImage(named: "Format 5.5.png"),
        UIImage(named: "Search 5.5.png")
    ]

    let pageCount = sixPlusImages.count
    pageControl.currentPage = 0
    pageControl.numberOfPages = pageCount

    for _ in 0..<pageCount {
        pageViews.append(nil)
    }

    let pagesScrollViewSize = scrollView.frame.size
    scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(sixPlusImages.count), height: pagesScrollViewSize.height)

    loadVisiblePages()
}

func loadPage(page: Int) {
    if page < 0 || page >= sixPlusImages.count {
        return
    }

    if let pageView = pageViews[page] {
    } else {
        var frame = scrollView.bounds
        frame.origin.x = frame.size.width * CGFloat(page)
        frame.origin.y = 0.0

        let newPageView = UIImageView(image: sixPlusImages[page])
        newPageView.contentMode = .ScaleAspectFit
        newPageView.frame = frame
        scrollView.addSubview(newPageView)

        pageViews[page] = newPageView
    }
}

func loadVisiblePages() {
    let pageWidth = scrollView.frame.size.width
    let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))

    let firstPage = page - 1
    let lastPage = page + 1

    for var index = 0; index < firstPage; ++index {
        purgePage(index)
    }

    for index in firstPage...lastPage {
        loadPage(index)
    }

    for var index = lastPage+1; index < sixPlusImages.count; ++index {
        purgePage(index)
    }

    pageControl.currentPage = page
}

func scrollViewDidScroll(scrollView: UIScrollView) {
    loadVisiblePages()
}

func purgePage(page: Int) {
    if page < 0 || page >= sixPlusImages.count {
        return
    }

    if let pageView = pageViews[page] {
        pageView.removeFromSuperview()
        pageViews[page] = nil
    }
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}

以下是视图层次结构的样子:

enter image description here

此外,滚动视图允许我向任何方向滚动,而不是像应该的那样水平滚动。我无法理解为什么会这样做,因为我使用的其他滚动视图并没有这样做。

有人看到任何问题吗?

0 个答案:

没有答案