Search code examples
iosobjective-cuiviewcarouselicarousel

UIView as items of a carousel


I want to use carousel in my objective-c application. I have an UIViewController containing an UIView (with a specific width and height). The content of this UIView must be as a carousel: Every item of my carousel should have an image and some text. I want also to have under the carousel, points (little circles). The points indicate the number of items and the point of the current item should have a different color than the other points. I found that the most famous carousel library is the iCarousel.

My question: How can I use the iCarousel having UIViews as items?

Edit:

I added iCarousel to my project, made the iCarousel as subClass of my UIView in the storyboad as @property (weak, nonatomic) IBOutlet iCarousel *carouselView;. Then in myViewController.h I added @interface myViewController : UIViewController<iCarouselDataSource>.

In myViewController.m:

    - (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
    {
        return 4;
    }

-(UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {

    self.carouselTitle.text = [self.titleDataSource objectAtIndex:index];
    self.carouselImage.image = [UIImage imageNamed:[self.imageDataSource objectAtIndex:index]];

    return self.carouselView;
}

The problem now is that when I run my application, it crash mentioning this line in the iCarousel.m : [_contentView addSubview:[self containView:view]]; (line 1260)

Any help please?


Solution

  • iCarousel uses a dataSource (similar to UITableView), that you need to implement. The main method

        -(UIView)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
    

    Lets you create views for each item on the fly. You can ignore reusingView if you want, but if all of the views in the carousel are the same type, then it will be faster to set properties on it and return it instead of creating a new one.

    Look at the sample: https://github.com/nicklockwood/iCarousel/blob/master/Examples/Basic%20iOS%20Example/iCarouselExampleViewController.m

    You need to:

    1. Implement iCarouselDataSource
    2. Set the carousel dataSource to the viewController (the sample does this in the XIB)
    3. implement the dataSource methods numberOfItemsInCarousel and viewForItemAtIndex...

    EDITED QUESTION RESPONSE:

    You are supposed to return new views that represent just the single carousel card for the item, not self.carouselView. It should either be a completely newly allocated object or the passed in reusingView:view, which you can change the properties of (it's passing you old views that have gone offscreen and can be updated).

    I strongly recommend you look at the examples in the project (especially the Basic one) and run and understand them.