How to insert Cell in UICollectionVIew Programmatically?
...By referring to UICollectionView documentation
You can accomplish:
Inserting, Deleting, and Moving Sections and Items To insert, delete,
or move a single section or item, follow these steps:
- Update the data in your data source object.
- Call the appropriate method of the collection view to insert or delete the section or item.
It is critical that you update your data source before notifying the
collection view of any changes. The collection view methods assume
that your data source contains the currently correct data. If it does
not, the collection view might receive the wrong set of items from
your data source or ask for items that are not there and crash your
app. When you add, delete, or move a single item programmatically, the
collection view’s methods automatically create animations to reflect
the changes. If you want to animate multiple changes together, though,
you must perform all insert, delete, or move calls inside a block and
pass that block to the performBatchUpdates:completion: method. The
batch update process then animates all of your changes at the same
time and you can freely mix calls to insert, delete, or move items
within the same block.
From your Question: you can for example register A gesture Recognizer, and Insert a NEW cell by
doing the following:
in
// in .h
@property (nonatomic, strong) NSMutableArray *data;
// in .m
@synthesize data
//
- (void)ViewDidLoad{
//....
myCollectonView.dataSource = self;
myCollectionView.delegate = self;
data = [[NSMutableArray alloc] initWithObjects:@"0",@"1", @"2" @"3", @"4",
@"5",@"6", @"7", @"8", @"9",
@"10", @"11", @"12", @"13",
@"14", @"15", nil];
UISwipeGestureRecognizer *swipeDown =
[[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(addNewCell:)];
swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:swipeDown];
//..
}
-(void)addNewCell:(UISwipeGestureRecognizer *)downGesture {
NSArray *newData = [[NSArray alloc] initWithObjects:@"otherData", nil];
[self.myCollectionView performBatchUpdates:^{
int resultsSize = [self.data count]; //data is the previous array of data
[self.data addObjectsFromArray:newData];
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (int i = resultsSize; i < resultsSize + newData.count; i++) {
[arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
inSection:0]];
}
[self.myCollectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
} completion:nil];
}
How to create UICollectionViewCell programmatically
Your problem lies here. In your viewDidLoad()
, you're registering your collectionView cell twice. You are registering the collectionview's cell to your custom cell class in the first line and then in the second line you are registering it to the class UICollectionViewCell
.
collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
Just remove the second line and your code should work.
Add cell in UicollectionViewController in Swift when you press a button
You should attach a datasource (like an Array<>
) to your UICollectionView
in order to insert cells; this because you're returning a fixed number of cells (1) in the collectionView:numberOfItemsInSection:
delegate method.
The only method in UICollectionView
designated to insert new cells is insertItemsAtIndexPaths:
that requires first an update of the datasource behind.
This is a very simple example:
var items = ["a", "b", "c"]
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func didTapButton() {
// "logical" insert
let newChar = "d"
items.append(newChar)
// "graphical" insert
let newIndexPath = NSIndexPath(forItem: items.indexOf(newChar)!, inSection: 0)
collectionView.insertItemsAtIndexPaths([newIndexPath])
}
//other delegate methods of UICollectionView not implemented in this example
Also, take a look at this question and the answers: How to insert Cell in UICollectionVIew Programmatically?.
Creating a UICollectionView programmatically
Header file:--
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
UICollectionView *_collectionView;
}
Implementation File:--
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:_collectionView];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 15;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor greenColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(50, 50);
}
Output---
iOS - How to init and insert UICollectionViewCell programmatically when data is ready?
I am unable to get a clear picture of the code and specific requirements of your AdSDK. So i will go ahead and write a pseudo code as per my understanding of what needs to be done. Here is what I purpose, instead of calling adFactory.loadAds()
into the UICollectionViewCell
object, you can perform this task into a different class object. Let say AdLoader
So your add loader should be something like this.
class Adloader {
var adFactory = AdsSDKFactory()
typealias adLoadCompletionHandler = (adView: AdsObject) -> Void
var loadCompletion
func initLoader() {
//Set some properties for the Ads SDK
adFactory.nativeDelegate = self
// method from the SDK to request the Ad
adFactory.loadAds()
}
}
Once the ad is loaded, you can use a completion handler to get update the collection view.
func adObjectDidLoad(adView: AdsObject!) {
adLoadCompletionHandler(adView)
}
So your code can be something like this.
if (needToInsertAd) {
var newAd = Adloader.initLoader()
newAd.adLoadCompletionHandler {
//Code to insert cell at indexpath
}
}
Hope this helps you.
How can I programmatically insert UICollectionView into UITableViewCell ? [Swift]
declare collectionView in the TableViewCell swift file.
var viewPhotos: UICollectionView!
func reset(with cellData: CellData) {
self.data = cellData
viewPhotos.dataSource = self
viewPhotos.delegate = self
viewPhotos.reloadData()
}in the
init
function orawakeFromNib
check if photoCollectionView is initialized and add it to the cell.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
viewPhotos = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
viewPhotos.collectionViewLayout = layout
viewPhotos.showsHorizontalScrollIndicator = false
viewPhotos.isPagingEnabled = true
viewPhotos.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: PhotoCollectionViewCell.cellIdentifier)
- Add UICollectionView Datasource and Delegate To the UITableViewCell
extension TableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection > section: Int) -> Int {
return photoUrls?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCollectionViewCell.cellIdentifier, for: indexPath) as! PhotoCollectionViewCell
if let value = photoUrls {
cell.reset(with url: value[indexPath.row]);
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: kPhotoWidth, height: kPhotoHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout > collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
}
- PhotoCollectionViewCell
create a PhotoCollectionViewCell derived from UICollectionViewCell
and add a UIImageView, and make all edge constraints to 0 to the
superview. load UIImageView based on photoUrl.
Related Topics
How to List (Almost) All Emojis in Swift for iOS 8 Without Using Any Form of Lookup Tables
Removing Object from Array in Swift 3
Info.Plist Utility Error: "Info.Plist Couldn't Be Opened Because There Is No Such File"
iOS 10 Rich Media Push Notification (Media Attachment) in Objective-C
Restkit and Saving to Coredata as Nsmanagedobject
Swift - Must Call a Designated Initializer of the Superclass Skspritenode Error
What Is the Impact of the "Requires Full Screen" Option in Xcode for an Iphone-Only App
How to Implement Localization in Swift Ui
Less Blur with 'Visual Effect View with Blur'
What Is Container View in iOS 5 Sdk
React-Native iOS Not Showing Images (Pods Issue)
Pulling Data from a Cmsamplebuffer in Order to Create a Deep Copy
Delete Cell from Uicollectionview Without Reloading from Top
Uinavigationcontroller Interactivepopgesturerecognizer Working Abnormal in iOS7
Linker Error When Accessing Application Module in UI Tests in Xcode 7.1