Ioscollectionview Ad Unlimited scrolling (Swift implementation)

Source: Internet
Author: User
Tags uikit

Today the company's interns ran over to ask me the General app ads on the infinite Scroll is how to achieve, just a long time no blog, decided to write down, as far as possible to help those in the Just learning iOS program ape.

To do a small demo, probably achieve the effect as shown:

Basic implementation Ideas:

1. In the place where you need to place unlimited scrolling display data, put his data on the original basis to expand the data you want to show three times times. (Of course the enlargement twice times is also possible, three times times the words, the better demo)

   // MARK:-Set the data source    Func CollectionView (_ Collectionview:uicollectionview, Numberofitemsinsection section:int), Int {//          Print (self.arrayM.count)        return3    }

2. When the timer is in effect, or in the drag case to scroll to the eighth time, set the collectionview.contentoffset.x at this time is equal to scroll to the third cell contentoffset.x

if collectionview.contentoffset.x = = CGFloat (31) * self.collectionView.bounds.width {             1) * self.collectionView.bounds.width        }

3. When dragged to the No. 0 cell, set the collectionview.contentoffset.x at this time equal to the contentoffset.x of the Sixth cell

if 0 {            = cgfloat (21) * self.collectionView.bounds.width                    }

The code is as follows:

I used 5 photos in my code, so I should have a total of 15 cells

Import UIKitclassViewcontroller:uiviewcontroller, Uicollectionviewdatasource, uicollectionviewdelegate {@IBOutlet weak var Collec Tionview:uicollectionview!var timer:timer?var arraym: [Bomodel]=[] {didset {self.collectionView.reloadData ()}}StaticLet Cellid ="Cell"    Overridefunc viewdidload () {super.viewdidload () Self.collectionView.dataSource=Self self.collectionview.Delegate= Self//Loading DataLoadData () self.collectionView.register (Uinib.init (nibname:"Bocollectionviewcell", Bundle:nil), ForCellWithReuseIdentifier:ViewController.CellID)//Set CollextionviewSetupcollectionview ()//Turn on TimerStartimer ()}///loading data from Polistfunc LoadData () {Let Stemp:nsarray= Nsarray (ContentsOfFile:Bundle.main.path (forresource:"shops.plist", Oftype:nil)!)! forDictinchstemp {Let model= Bomodel.init (dict:dict as![String:any]) Self.arrayM.append (model)}}///set how cellection is laid out///    ///-Returns: one layout typeFunc setupcollectionflowlayout ()(uicollectionviewflowlayout) {Let FlowLayout=uicollectionviewflowlayout () flowlayout.itemsize=self.collectionView.bounds.size flowlayout.minimumlinespacing=0flowlayout.minimuminteritemspacing=0flowlayout.scrolldirection=. Horizontal Flowlayout.sectioninset= Uiedgeinsetsmake (0,0,0,0)        returnFlowLayout}///Set CollectionViewFunc Setupcollectionview ()() {self.collectionView.collectionViewLayout=self.setupcollectionflowlayout () self.collectionView.showsVerticalScrollIndicator=falseSelf.collectionView.showsHorizontalScrollIndicator=falseself.collectionView.isPagingEnabled=true            }        //MARK:-Set the data sourceFunc CollectionView (_ Collectionview:uicollectionview, Numberofitemsinsection section:int)Int {//print (Self.arrayM.count)        returnSelf.arrayM.count *3} func CollectionView (_ Collectionview:uicollectionview, Cellforitemat Indexpath:indexpath)-Uicollectionviewcell {Let cell= Self.collectionView.dequeueReusableCell (WithReuseIdentifier:ViewController.CellID, for: Indexpath) as!Bocollectionviewcell Cell.model= Self.arraym[indexpath.row%Self.arrayM.count]returncell}//MARK:-Implementing proxy methodsFunc scrollviewdidenddecelerating (_ Scrollview:uiscrollview) {//Contentoffset.x = = 0 o'clock, reset the value of Contentoffset.x        ifCollectionview.contentoffset.x = =0{self.collectionview.contentoffset.x= CGFloat (2* Self.arrayM.count-1) *Self.collectionView.bounds.width}//Reset the value of the contentoffset.x when the last cell is reached        ifCollectionview.contentoffset.x = = CGFloat (3* Self.arrayM.count-1) *Self.collectionView.bounds.width {self.collectionview.contentoffset.x= CGFloat (Self.arrayM.count-1) *Self.collectionView.bounds.width}}///Turn on Timerfunc Startimer () {Let timer= Timer.init (timeinterval:1, Target:self, selector: #selector (viewcontroller.nextpage), Userinfo:nil, repeats:true)        //This code involves the knowledge of runloop and the main thread, and no other UI action can be performed on the interface.RunLoop.main.add (Timer, forMode:RunLoopMode.commonModes) Self.timer=Timer}///automatically jumps to the next page after 1 secondsfunc nextPage () {//if the last one arrives, it becomes the fourth one.        ifCollectionview.contentoffset.x = = CGFloat (3* Self.arrayM.count-1) *Self.collectionView.bounds.width {self.collectionview.contentoffset.x= CGFloat (Self.arrayM.count-1) *Self.collectionView.bounds.width}Else {            //every second, contentoffset.x increases the width of a cellSelf.collectionview.contentoffset.x + =Self.collectionView.bounds.size.width}}///when the CollectionView starts to drag, cancel the timerFunc scrollviewwillbegindragging (_ Scrollview:uiscrollview) {Self.timer?. Invalidate () Self.timer=Nil}///when the user stops dragging, turn on the timerFunc scrollviewwillenddragging (_ Scrollview:uiscrollview, Withvelocity velocity:cgpoint, TargetContentOffset: Unsafemutablepointer<cgpoint>) {Startimer ()}}

The plist file looks like this:

The dictionary used to turn the model because of the relatively simple conversion, wrote a:

Import UIKit class Bocollectionviewcell:uicollectionviewcell {    @IBOutlet weak var imageview:uiimageview!     var Model:bomodel? {        Didset {            else  {                return            }                                    = image        }    }     Override func awakefromnib () {        super.awakefromnib ()     }}

Customizing the contents of the Collectionviewcell class:

Import UIKit class Bocollectionviewcell:uicollectionviewcell {    @IBOutlet weak var imageview:uiimageview!     var Model:bomodel? {        Didset {            else  {                return            }                                    = image        }    }     Override func awakefromnib () {        super.awakefromnib ()     }}

Attached: In fact, this method to achieve unlimited scrolling, the use of a little bit of skill, computer testing may have a little flaw.

Ioscollectionview Ad Unlimited scrolling (Swift implementation)

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.