Swift uses CollectionView to implement picture Carousel encapsulation that's simple

Source: Internet
Author: User

Preface: This article you can learn custom view, create CollectionView, use of protocol, timer;


Homemade pictures


First on the Demo:github on the package good download is ready to use, please star Thanks
First create a new view that inherits from UIView, and it is implemented with CollectionView, so we need to sign two protocol codes as follows:

let sectionnum:  Int = 100 //area number let width = uiscreen.mainscreen (). Bounds.size.width //screen width let height = uiscreen.mainscreen (). Bounds.size.width //screen height //because to implement a carousel picture you can click Define a protocol //protocol protocol xtcycleviewdelegate {func didselectindexcollectionviewcell (index:int)->void}        
UIView, UICollectionViewDelegate, UICollectionViewDataSource{

Variables to use and create views

    var delegate:Xtcycleviewdelegate?var Cyclecollectionview: uicollectionview? var images = nsmutablearray () var Pagecontrol = uipagecontrol () var flowlayout = uicollectionviewflowlayout () var timer = NSTimer () Span class= "Hljs-keyword" >override init (frame: CGRect) {super. init (frame:frame) self.createsubviews (frame)} required Span class= "Hljs-keyword" >init? (Coder Adecoder: nscoder) {fatalerror ( "Init (coder:) have not been Implemented ")}               

Layout the necessary UI and create timers

Func Createsubviews (frame:CGRect) {Cyclecollectionview =Uicollectionview. Init (frame:CGRectMake (0,0, Frame. Size. width, Frame. Size. height), collectionviewlayout:flowlayout) FlowLayout. itemsize =Cgsizemake (frame. Size. width, Frame. Size. height); FlowLayout. minimuminteritemspacing =0; FlowLayout. minimumlinespacing =0; FlowLayout. scrolldirection =Uicollectionviewscrolldirection. Horizontal; cyclecollectionview!. BackgroundColor =Uicolor. Lightgraycolor () cyclecollectionview!. pagingenabled =True cyclecollectionview!. DataSource =Self cyclecollectionview!. Delegate =Self cyclecollectionview!. Showshorizontalscrollindicator =False cyclecollectionview!. Showsverticalscrollindicator =False cyclecollectionview!. registerclass (Zjcustomcyclecell. Self, Forcellwithreuseidentifier:"Cellid")Self. Addsubview (cyclecollectionview!) Pagecontrol =Uipagecontrol. Init (frame: CGRectMake (0, 0, frame. Size. Width/ 2, )) Pagecontrol . Center = Cgpointmake (frame. Size. Width/ 2, Frame. Size. Height- 20); self. Addsubview (Pagecontrol); Self . AddTimer ()}                

Timer initialization

func addTimer(){        let timer1 = NSTimer.init(timeInterval: 2, target: self, selector: "nextPageView", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(timer1, forMode: NSRunLoopCommonModes) timer = timer1 }

Destroying timers

func removeTimer(){        self.timer.invalidate() }

Implementing circular Scrolling

 FuncReturnindexpath()nsindexpath{var Currentindexpath = cyclecollectionview!. Indexpathsforvisibleitems (). Last Currentindexpath =Nsindexpath.Init (forrow: (Currentindexpath?. Row)!, Insection:sectionnum/2) cyclecollectionview!. Scrolltoitematindexpath (currentindexpath!, Atscrollposition:Uicollectionviewscrollposition.Left, animated:Falsereturn currentindexpath!; }Funcnextpageview () {let IndexPath = Span class= "Hljs-keyword" >self.returnindexpath () var item = indexpath.row + 1; var section = indexpath.section; if item = = images. count {item = 0 section++}  Self.pageControl.currentPage = Item; let Nextindexpath = nsindexpath. Init (Forrow:item, insection:section) cyclecollectionview!. Scrolltoitematindexpath (Nextindexpath, atscrollposition: uicollectionviewscrollposition. left, Animated: true)}       

CollectionView Delegate

     Reusing poolsFuncCollectionView(Collectionview:uicollectionview, Cellforitematindexpath Indexpath:nsindexpath)Uicollectionviewcell {The custom cell that is used here will be labeled with the custom cell codeLet cell = Collectionview.dequeuereusablecellwithreuseidentifier ("Cellid", Forindexpath:indexpath)as!ZjcustomcyclecellThis label implements the display number, which represents the first few pictures cell.labelTitle.text =NSString (format:"%d", Indexpath.row)AsStringHere is the picture assignmentLet URL:String =Self.images[indexpath.row]as!StringHere I am using an assignment picture of the three-party library, to see their preferences, for the convenience I did not write their own cell.imageView.hnk_setImageFromURL (nsurl. init (string:url)!) return Cell} func  Numberofsectionsincollectionview (Collectionview:uicollectionview), int {return sectionnum}  Func collectionview (Collectionview:uicollectionview, Numberofitemsinsection section:int), int {// The number of Pagecontrol is given here pagecontrol.numberofpages = images. count return images. Count}                
    //  重新添加定时器    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.addTimer() } // 手动滑动的时候销毁定时器 func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.removeTimer() }

Set the current Pagecontrol

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {        let page = (Int(scrollView.contentOffset.x) / Int(width)) % images.count pageControl.currentPage = page }

click Method

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {        self.delegate?.didSelectIndexCollectionViewCell(indexPath.row) }

Here's my code in the custom cell

    var urlimage:String =""var ImageView =Uiimageview ()var labeltitle =UILabel ()OverrideInit (frame:CGRect) {Super.Init (Frame:frame)Self.createsubviews (frame)} requiredinit? (Coder Adecoder: nscoder) {fatalerror ( "Init (coder:) have not been Implemented ")} func createSubviews< Span class= "Hljs-params" > (frame:cgrect) {ImageView = uiimageview. Init (frame: cgrectmake (0, 0, Frame.size.width, Frame.size.height)) self.contentview.addsubview (ImageView) Labeltitle = uilabel. Init (frame: cgrectmake (10, 10, 30, 30)) Imageview.addsubview (Labeltitle)}      

The package is basically done, so let's see how to use

        // 创建        let cycle = XTCycleScrollView.init(frame: CGRectMake(0, 70, width, 175)) // 要实现点击需要制定代理人 cycle.delegate = self; // 图片链接数组 let images: NSMutableArray = ["", "", "", ""] // 数组赋值 cycle.images = images self.view.addSubview(cycle)

Implementing Proxy methods

func didSelectIndexCollectionViewCell(index: Int) {        print("\\(index)") }

Summary: This will achieve a simple picture carousel effect, and with a click Method, you can see here on the point of praise it. Ha ha



Wen/summer Then (Jane book author)
Original link: http://www.jianshu.com/p/f5fa66699a96
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Swift uses CollectionView to implement picture Carousel encapsulation that's simple

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.