IOS图像查看器以swift,编程方式

时间:2014-09-02 21:02:52

标签: ios image swift uiimageview

我正在尝试使用此动画创建一个imageViewer this toturial

我想使用“PagedScrollViewController”示例并使用swift, 我能够在屏幕上显示图像,但是滚动有问题。

滚动不会在页面/照片之间停止,它会自由滚动,因此我总是调用loadVisiblePages每个滚动的像素。

可能我错过了什么,你能帮帮我吗? 这就是我在做的事情:

谢谢

import UIKit

class PagedScrollViewController:UIViewController,UIScrollViewDelegate {


var pageImages:[UIImage] = [UIImage]()
var pageViews:[UIView?] = [UIView]()

var scrollView:UIScrollView = UIScrollView()
var pageControl:UIPageControl = UIPageControl()


func loadVisiblePages() {
    // First, determine which page is currently visible
    var pageWidth:CGFloat = self.scrollView.frame.size.width;

    var page = Int(floor((self.scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)));

    // Update the page control
    self.pageControl.currentPage = page;

    // Work out which pages we want to load
    var firstPage = page - 1;
    var lastPage = page + 1;

    // Purge anything before the first page
    for (var i=0; i<firstPage; i++) {
        println("1) purge index \(i)")
        self.purgePage(i)
    }
    for (var i=firstPage; i<=lastPage; i++) {
        println("2) load index \(i)")
        self.loadPage(i)
    }
    for (var i = lastPage+1 ; i < self.pageImages.count ; i++) {
        println("3) purge index \(i)")
        self.purgePage(i)
    }
}
//
func loadPage(page:Int) {
    if page < 0 || page >= self.pageImages.count {
        // If it's outside the range of what we have to display, then do nothing
        return;
    }

    // Load an individual page, first seeing if we've already loaded it
    var pageView:UIView? = self.pageViews[page];
    if pageView == nil {
        var frame:CGRect = self.scrollView.bounds;
        //frame.origin.x = frame.size.width * CGFloat(page)
        frame.origin.x = 320.0 * CGFloat(page)
        frame.origin.y = 0.0

        var newPageView:UIImageView = UIImageView(image: self.pageImages[page])
        newPageView.contentMode = UIViewContentMode.ScaleAspectFit;
        newPageView.frame = frame;
        self.scrollView.addSubview(newPageView)
        self.pageViews[page] = newPageView
    }
}

func purgePage(page:Int) {
    if page < 0 || page >= self.pageImages.count {
        // If it's outside the range of what we have to display, then do nothing
        return;
    }

    // Remove a page from the scroll view and reset the container array
    var pageView:UIView? = self.pageViews[page];
    if pageView != nil {
        pageView?.removeFromSuperview()
        self.pageViews[page] = UIView()//nil
    }
}




override func viewDidLoad() {
    super.viewDidLoad()


    self.title = "Paged";

    self.view.backgroundColor = UIColor.blueColor()

    // Set up the image we want to scroll & zoom and add it to the scroll view
    self.pageImages.append(UIImage(named: "first.png"))
    self.pageImages.append(UIImage(named: "second.png"))
    self.pageImages.append(UIImage(named: "first.png"))
    self.pageImages.append(UIImage(named: "second.png"))
    self.pageImages.append(UIImage(named: "first.png"))

    var pageCount = self.pageImages.count

    self.scrollView.delegate = self
    //self.tableView.showsHorizontalScrollIndicator = false
    //self.tableView.showsVerticalScrollIndicator = false

    // Set up the page control
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = pageCount;

    self.pageControl.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addSubview(self.pageControl)
    self.view.addSubview(self.scrollView)


    //Set layout
    var viewsDict = Dictionary <String, UIView>()
    viewsDict["control"] = self.pageControl;
    viewsDict["scrollView"] = self.scrollView;

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[control]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollView(400)]-[control]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))


    // Set up the array to hold the views for each page
    for (var i = 0; i < pageCount; ++i) {
        self.pageViews.append(nil)

    }
}


override func viewDidAppear(animated:Bool) {
    super.viewDidAppear(animated)

    // Set up the content size of the scroll view
    var pagesScrollViewSize:CGSize = self.scrollView.frame.size;
    self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(self.pageImages.count), pagesScrollViewSize.height);

    // Load the initial set of pages that are on screen
    self.loadVisiblePages()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

    //        self.scrollView = nil
    //        self.pageControl = nil
    //        self.pageImages = nil
    //        self.pageViews = nil
}

func scrollViewDidScroll(scrollView:UIScrollView ) {
    // Load the pages which are now on screen
    self.loadVisiblePages()
    println("scrollViewDidScroll")
}



}

1 个答案:

答案 0 :(得分:2)

问题是我没有将'self.scrollView.pagingEnabled'设置为true。我现在还在UIKit。 我做了一些性能改进的方式,只在需要时才调用布局, 希望有人会发现这个usfull :) 感谢http://www.raywenderlich.com

import UIKit

class PagedScrollViewController:UIViewController,UIScrollViewDelegate {

    var pageImages:[UIImage] = [UIImage]()
    var pageViews:[UIView?] = [UIView]()

    var scrollView:UIScrollView = UIScrollView()
    var pageControl:UIPageControl = UIPageControl()

    var viewingPage = -1

    func loadVisiblePages() {
        // First, determine which page is currently visible
        var pageWidth:CGFloat = self.scrollView.frame.size.width;
        var page = Int(floor((self.scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)));

        /* 
            Check that page have changed,
            in case that user drag left in first page, or drag right in last page
            a 'scrollViewDidEndDecelerating' is fired
        */
        if viewingPage != page {

            // Update the page control
            self.pageControl.currentPage = page;

            // Work out which pages we want to load
            var firstPage = page - 1;
            var lastPage = page + 1;

            // Purge anything before the first page
            for (var i=0; i<firstPage; i++) {
                self.purgePage(i)
            }
            for (var i=firstPage; i<=lastPage; i++) {
                self.loadPage(i)
            }
            for (var i = lastPage+1 ; i < self.pageImages.count ; i++) {
                self.purgePage(i)
            }

            viewingPage = page
        }

    }

    func loadPage(page:Int) {
        if page < 0 || page >= self.pageImages.count {
            // If it's outside the range of what we have to display, then do nothing
            return;
        }

        // Load an individual page, first seeing if we've already loaded it
        var pageView:UIView? = self.pageViews[page];
        if pageView == nil {
            var frame:CGRect = self.scrollView.bounds;
            //frame.origin.x = frame.size.width * CGFloat(page)
            frame.origin.x = 320.0 * CGFloat(page)
            frame.origin.y = 0.0

            var newPageView:UIImageView = UIImageView(image: self.pageImages[page])
            newPageView.contentMode = UIViewContentMode.ScaleAspectFit;
            newPageView.frame = frame;
            self.scrollView.addSubview(newPageView)
            self.pageViews[page] = newPageView
        }
    }

    func purgePage(page:Int) {
        if page < 0 || page >= self.pageImages.count {
            // If it's outside the range of what we have to display, then do nothing
            return;
        }

        // Remove a page from the scroll view and reset the container array
        var pageView:UIView? = self.pageViews[page];
        if pageView != nil {
            pageView?.removeFromSuperview()
            self.pageViews[page] = nil
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Image viewer";

        self.view.backgroundColor = UIColor.blueColor()

        // Set up the image we want to scroll & zoom and add it to the scroll view
        self.pageImages.append(UIImage(named: "message_full.png"))
        self.pageImages.append(UIImage(named: "heart_full"))
        self.pageImages.append(UIImage(named: "star_full.png"))
        self.pageImages.append(UIImage(named: "second.png"))
        self.pageImages.append(UIImage(named: "first.png"))

        var pageCount = self.pageImages.count

        self.scrollView.pagingEnabled = true
        self.scrollView.delegate = self
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.showsVerticalScrollIndicator = false

        // Set up the page control
        self.pageControl.currentPage = 0;
        self.pageControl.numberOfPages = pageCount;

        self.pageControl.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)

        self.view.addSubview(self.pageControl)
        self.view.addSubview(self.scrollView)


        //Set layout
        var viewsDict = Dictionary <String, UIView>()
        viewsDict["control"] = self.pageControl;
        viewsDict["scrollView"] = self.scrollView;

        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[control]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollView(400)]-[control]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict))

        // Set up the array to hold the views for each page
        for (var i = 0; i < pageCount; ++i) {
            self.pageViews.append(nil)
        }
    }


    override func viewDidAppear(animated:Bool) {
        super.viewDidAppear(animated)

        // Set up the content size of the scroll view
        var pagesScrollViewSize:CGSize = self.scrollView.frame.size;
        self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(self.pageImages.count), pagesScrollViewSize.height);

        // Load the initial set of pages that are on screen
        self.loadVisiblePages()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //TODO make cleaning
        //        self.scrollView = nil
        //        self.pageControl = nil
        //        self.pageImages = nil
        //        self.pageViews = nil
    }


    func scrollViewDidEndDecelerating(scrollView: UIScrollView!) {
        self.loadVisiblePages()
    }

}