pre select/highlight UICollectionViewCell on first load of view

uicollectionview supplementary view
uicollectionview cell selection color
uicollectionview select item programmatically swift
uicollectionview selection
uicollectionview indexpath for selected cell
uicollectionview multiple selection
uicollectionview selected cell background color swift
uicollectionview sections

Im trying to preselect the first object/UICollectionViewCell in the UICollectionView? I have tried:

self.dateCollectionView.allowsMultipleSelection=NO;

[self.dateCollectionView selectItemAtIndexPath:0 animated:YES scrollPosition:UICollectionViewScrollPositionLeft];
[self collectionView:self.dateCollectionView didSelectItemAtIndexPath:0];
[self.dateCollectionView reloadData];

in viewDidLoad.

Here are my UICollectionView methods;

 -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

  return self.titles.count;
 }

 -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.backgroundColor= [UIColor clearColor];
    UILabel * dateLabel = (UILabel *)[cell viewWithTag:1];
    UILabel * subText = (UILabel *)[cell viewWithTag:2];
    subText.text=self.titles[indexPath.row];
    subText.adjustsFontSizeToFitWidth=YES;
    if (cell.selected) {
        cell.backgroundColor = [UIColor blueColor]; // highlight selection
    }
    else
    {
        cell.backgroundColor = [UIColor redColor]; // Default color
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

 UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}

- (BOOL)collectionView:(UICollectionView *)collectionView
 shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView
 shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    return YES;
}

In viewDidAppear:

NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection:0];
[self.dateCollectionView selectItemAtIndexPath:indexPathForFirstRow animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.dateCollectionView didSelectItemAtIndexPath:indexPathForFirstRow];

Changing the Appearance of Selected and Highlighted Cells, The first image When the cell's state changes to highlighted or selected, the collection view modifies the default background with the selected background when highlighting or selecting a cell. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView. The layout and presentation of cells is managed by the collection view and its corresponding layout object. To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the content View property. Do not directly add subviews to the cell itself.

For Swift 3.0.1 You can try this:

self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])

or

self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))

For Objective-C You can try this:

self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];

Note: You should use it in viewDidAppear

UICollectionViewCell selection made easy..!!, Im trying to preselect the first object/UICollectionViewCell in the UICollectionView​? I have tried: 17 pre select/highlight UICollectionViewCell on first load of view Apr 23 '15 14 Problems with Cocoa Pods Dec 3 '14 12 Auto property synthesize will not synthesize property - new warning iOS8.3 Apr 15 '15

For swift 3

Use collectionView.selectItem with-in this overload collectionView(UICollectionView, IndexPath)

This is my code, in this code I pre selected row with indexPath.row = 0

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ScenarioCollectionView.dequeueReusableCell(withReuseIdentifier: "ReuseScenarioCollectionViewCell", for: indexPath as IndexPath) as! ScenarioCollectionViewCell

    if (indexPath.row == 0){
        collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
        cell.layer.borderColor=UIColor.gray.cgColor        
    }else{
        cell.layer.borderColor=UIColor.white.cgColor
    }
    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.borderColor = UIColor.gray.cgColor
        }

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath as IndexPath)
    cell?.layer.borderColor = UIColor.white.cgColor
    collectionView.deselectItem(at: indexPath, animated: true)
}

UICollectionView Tutorial: Getting Started, Showing selection of a particular collection view cell is a very In your custom UICollectionViewCell subclass, just override isSelected property, i.e. The selected state is toggled when the user lifts up from a highlighted cell. 9 pre select/highlight UICollectionViewCell on first load of view Feb 1 '17. 8 Fade/dissolve when changing UIImageView's image Mar 10 '17. 7 PHAsset to UIImage Nov 11

I solved this by subclassing UICollectionView and selecting needed item in layoutSubviews:

class InitialSelectionCollectionView: UICollectionView {

   var initialSetupPerformed: Bool = false
   var initialSelectedIndexPath: IndexPath!

   override func layoutSubviews() {
       super.layoutSubviews()

       if !initialSetupPerformed && initialSelectedIndex != nil{
           selectItem(at: initialSelectedIndexPath, animated: false, scrollPosition: .centeredHorizontally)

           initialSetupPerformed = true
       }
   }
}

Then, when you init your custom collection view, just set needed IndexPath to initialSelectedIndexPath

UICollectionView Tutorial: Reusable Views, Selection and Reordering, In this tutorial, you'll get hands-on experience with UICollectionView by creating your own First, take a look at the example of the finished project. Select the single cell in the collection view and set the Reuse Identifier to You're using the pre-made flow layout for this project, since it's nice and easy to  </select> As you can see, the initially selected item is the first item on the list. Pre-Render Selection. In order to pre-select an item on the drop down list you can do so prior to the page being rendered by adding a selected="selected" attribute inside the required option. So if we wish to pre-select item 3 for the above example, we can use

For me, putting it in viewDidAppear: cause a second to select, so the user will see both states (i.e. not selected, and selected). To avoid this, I put it in viewWillAppear: instead and worked like a charm

override func viewWillAppear(_ animated: Bool) {
    let selectedIndexPath = IndexPath(item: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: .left)
}

UICollectionView - Select first cell as View Will Appear, First, you'll learn to select a single cell and change the collection view layout to display the selected cell in a larger size. The selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.

Quick Tutorial: Preselect UITableViewCell/UICollectionViewCell , In my collection view I need to select the first cell as soon as the view appear. I want the current student item be selected/highlighted. How can I do this? I know there Firstly in view did load I did: override func viewDidLoad() { super. None​) } Here I default to selecting the first cell, you would use StudentArray.indexOf to​  The collection view gets its data from the data source object, which is an object that conforms to the UICollection View Data Source Protocol and is provided by your app. Data in the collection view is organized into individual items, which can then be grouped into sections for presentation. An item is the smallest unit of data you want to present.

Collection View Tutorial: Handling Single and Multiple Selection, I allow my users to set these properties upon initialization, and view them and change them as desired. To do this, I have a UITableView with a UICollectionView with cells that upon load with the ability to deselect them or select unselected cells. The first thing is to set the cell's “isSelected” to True. Option 1: The simple option. We can simply set the itemSize width on Flow Layout to be the same as the collection view width. This does work but has a few caveats. First, section insets need to be accounted for and second this will not work as soon the device is rotated to landscape.

Smooth Scrolling in UITableView and UICollectionView, In the past two tutorials, we covered the basics of UICollectionView and As mentioned before, the Collection View works in a way pretty much like Table View. First, we'll improve the Recipe app to handle single selection. the cell changes to the highlighted state and then to the selected state. Starting with AutoCAD 2016, you can also change the color of the highlight by using the SELECTIONEFFECTCOLOR system variable. Turn off hardware acceleration. Optionally, you may turn off hardware acceleration via the GRAPHICSCONFIG command to disable the selection effects.

Comments
  • Thanks you for that!
  • layoutIfNeeded saved my day!