Pre select/highlight UICollectionViewCell при первой загрузке представления
Я пытаюсь предварительно выбрать первый объект /UICollectionViewCell в UICollectionView? Я пробовал:
self.dateCollectionView.allowsMultipleSelection=NO;
[self.dateCollectionView selectItemAtIndexPath:0 animated:YES scrollPosition:UICollectionViewScrollPositionLeft];
[self collectionView:self.dateCollectionView didSelectItemAtIndexPath:0];
[self.dateCollectionView reloadData];
в viewDidLoad
.
Вот мои методы UICollectionView
;
-(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;
}
Ответы
Ответ 1
В viewDidAppear
:
NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection:0];
[self.dateCollectionView selectItemAtIndexPath:indexPathForFirstRow animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.dateCollectionView didSelectItemAtIndexPath:indexPathForFirstRow];
Ответ 2
Для Swift 3.0.1 Вы можете попробовать следующее:
self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
или
self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))
Для Objective-C Вы можете попробовать следующее:
self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
Примечание.. Вы должны использовать его в viewDidAppear
Ответ 3
Для быстрого 3
Используйте collectionView.selectItem
с этой перегрузкой collectionView(UICollectionView, IndexPath)
Это мой код, в этом коде я предварительно выбрал строку с 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)
}
Ответ 4
Я решил это путем подкласса UICollectionView
и выбрав нужный элемент в 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
}
}
}
Затем, когда вы создаете собственное пользовательское представление коллекции, просто установите необходимый IndexPath
в initialSelectedIndexPath
Ответ 5
Для меня, помещая это в viewDidAppear:
секунду выбирать, таким образом, пользователь увидит оба состояния (то есть не выбрано, а выбрано). Чтобы избежать этого, я поместил это в viewWillAppear:
вместо этого и работал как шарм
override func viewWillAppear(_ animated: Bool) {
let selectedIndexPath = IndexPath(item: 0, section: 0)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: .left)
}
Ответ 6
Для Swift 3:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//auto selected 1st item
let indexPathForFirstRow = IndexPath(row: 0, section: 0)
self.collectionView?.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: .top)
}
Ответ 7
[self.collectionView reloadData];
[self.collectionView layoutIfNeeded]; //important
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];
Ответ 8
быстрый код для выбора ячейки первоначально
func selectinitialCell() {
let cell = venueTypeCollectionView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as! SearchTypeCollectionViewCell
self.indexPathOfSelectedItem = NSIndexPath(forItem: 0, inSection: 0)
cell.venueType.textColor = UIColor.whiteColor()
cell.selected = true
}
но это не вызывает функцию делегата, такую как didSelectItemAtIndexPath, didDeselectItemAtIndexPath.
Ответ 9
Необходимо переопределить viewDidLayoutSubviews, чтобы предварительно выбрать элемент без анимации при первом запуске:
стриж
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let indexPath = IndexPath(item: 8, section: 1)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)
}
ObjC
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:2];
[self.collectionView selectItemAtIndexPath:indexPath animated:NO atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
}
Ответ 10
Swift 4.2 & 5
UICollectionViewCell
class YouCollectionViewCell: UICollectionViewCell {
let selectedColor = UIColor.blue
let unSelectedColor = UIColor.black
override var isSelected: Bool {
didSet {
self.backgroundColor = isSelected ? selectedColor : unSelectedColor
}
}
}
UIViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YouCollectionViewCell
if indexPath.row == 0 {
cell.isSelected = true
}
return cell
}