Monday 25 August 2014

masksToBounds and cornerRadius : An interesting catch

Every view has a layer as its backing property. The relevance of masksToBounds is that it tells the layer to clip the View to its bounds.
What i read on multiple websites was a little misleading, such as:
"It depends on masksToBounds which determines if the sublayers are clipped to the receiver’s bounds. So If YES, an implicit mask matching the layer bounds is applied to the layer, including the effects of the cornerRadius property." in a StackOverflow Post.

In this answer by sublayers this guy also means the VIEW that has the layer as its property. So when you set the cornerRadius of the layer, the layer gets rounded but the view overshadows  the layer. But when you set masksToBounds to YES, then the view gets clipped according to the layer and hence its corners also get rounded. :)

Hope this helps someone.

Wednesday 20 August 2014

UICollectionViewCell Selection and Deselection

Problem:

Today, i ran into a problem where i wanted to do some stuff on selection and deselection of a collectionView cell.
I inserted two delegate methods in my controller namely:

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


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

When i tapped on my collectionView cell the method didSelectItemAtIndexPath was getting called. But when i tapped on the same cell again the method didDeselectItemAtIndexPath did not get called instead didSelectRowAtIndexPath was getting called again, hence, the actions that i specified in didDeselectItemAtIndexPath were not running.


Solution:

Add    
 [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:nil]
to your didSelectItemAtIndexPath and also 

Add
 [collectionView deselectItemAtIndexPath:indexPath animated:NO]
to your  didDeselectItemAtIndexPath method to solve the problem.

After banging my head around for a while i realised that collectionView can't make out whether the cell is selected or deselected until we tell it so. Hence we tell the collectionView that we want this cell to be selected. What this does is that it makes the collectionView call the didDeselectItemAtIndexPath method the when we tap on the cell for the second time.

Additional Notes:

- Setting cell.selected = YES or NO does not solve the problem. Please try avoiding it as the Apple Documentation also says that "The preferred way to select the cell and highlight it is to use the selection methods of the collection view object."