2

Hello I have a UICollectionView. In a particular cell I have many views like UserProfileView, ProductView, CommentBoxView etc. In CommentBoxView there is a text view where the user can type and then post the comment. After posting the comment I want to focus that particular cell, from which cell user have posted the comment. For this I have used :

func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
  return IndexPath(row: 2, section: 0)
}

I am testing with the hardcoded value but still it is not coming. Please any one help me regarding this matter.

dr_barto
  • 5,723
  • 3
  • 26
  • 47
Gorib Developer
  • 587
  • 2
  • 13
  • 27

2 Answers2

3

Perhaps by "focus" you mean "scroll to." If you'd like to scroll to a cell, you should invoke

collectionView.scrollToItem(at: indexPath, scrollPosition: .centeredVertically, animated: true)

It may be useful to check out the documentation for this function.

As far as I know, while focus is a central concept in tvOS development, in iOS, its main function is to drive accessibility experiences. As such, I don't think it will have the effect you're expecting.

woodcutting
  • 271
  • 1
  • 9
  • where to write this code? after posting the comment? – Gorib Developer Jul 16 '18 at 05:13
  • sir how to pass indexPath in collectionView.scrollToItem(at: indexPath, scrollPosition: .centeredVertically, animated: true)? – Gorib Developer Jul 16 '18 at 05:28
  • Try something like `collectionView.scrollToItem(at: IndexPath(item: 2, section: 0), scrollPosition: .centeredVertically, animated: true)`. – woodcutting Jul 16 '18 at 12:52
  • @GoribDeveloper you need to write this code inside func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) method. – pulp Jun 17 '20 at 10:28
3

Try to use:

self.collectionView.scrollToItem(at:IndexPath(item: indexNumber, section: sectionNumber), at: .right, animated: false)
shiju86.v
  • 667
  • 5
  • 10