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 … Read more

Cell spacing in UICollectionView

Supporting the initial question. I tried to get the spacing to 5px on the UICollectionView but this does not work, as well with a UIEdgeInsetsMake(0,0,0,0)… On a UITableView I can do this by directly specifying the x,y coordinates in a row… Heres my UICollectionView code: #pragma mark collection view cell layout / size – (CGSize)collectionView:(UICollectionView*)collectionView … Read more

UICollectionView Self Sizing Cells with Auto Layout

This answer is outdated from iOS 14 with the addition of compositional layouts. Please consider updating the new API Updated for Swift 5 preferredLayoutAttributesFittingAttributes renamed to preferredLayoutAttributesFitting and use auto sizing Updated for Swift 4 systemLayoutSizeFittingSize renamed to systemLayoutSizeFitting Updated for iOS 9 After seeing my GitHub solution break under iOS 9 I finally got … Read more

Displaying images on another view controller when button is clicked

Swift 4 First, add a notification in each button action: NotificationCenter.default.post(name: Notification.Name(“buttonAIsPressed”), object: nil) now add a notification listener in the viewDidLoad of the collection view class and call the function in the selector: NotificationCenter.default.addObserver(self, selector: #selector(self.YourFunctionName), name: Notification.Name(“buttonAIsPressed”), object: nil) now whenever a button is pressed the function you named will be called.