我正在尝试在加载时预先选择第一个集合视图单元格但是在加载时未预先选择项目
用于预选集合视图单元格的代码在下面提供
MenuBar.m // Type UIView <UICollectionViewDelegate ,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
...
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
....
// below code in -(instancetype)initWithFrame:(CGRect)frame
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[collectionView selectItemAtIndexPath:selectedIndexPath
animated:false
scrollPosition:UICollectionViewScrollPositionNone];
....
// below code in -(instancetype)initWithFrame:(CGRect)frame
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
答案 0 :(得分:0)
在您的课程中实施此方法collectionView:didSelectItemAtIndexPath
预选是应该由UIViewController
控制的一部分逻辑
提供预选自定义视图的方法:
.h
档案:
- (void)preselectCellAt:(NSIndexPath *)indexPath;
您的.m
文件:
- (void)preselectCellAt:(NSIndexPath *)indexPath {
[collectionView selectItemAtIndexPath:indexPath
animated:false
scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:collectionView didSelectItemAtIndexPath:indexPath];
}
初始化ViewController
的超级视图UIView
:
- (Void)viewDidiAppear {
[super viewDidiAppear];
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.customView preselectCellAt:selectedIndexPath];
}
答案 1 :(得分:0)
您必须在selectedBackgroundView
中设置UICollectionViewCell
。
例如,如果您希望UICollectionViewCell
在选中时为绿色,则必须在UICollectionViewCell
类中编写此类代码
Objcective C
- (void)awakeFromNib() {
[super awakeFromNib];
UIView *selectedView = [[UIView alloc] initWithFrame: [self bounds]];
[selectedView setBackgroundColor: [UIColor greenColor]];
[self setSelectedBackgroundView: selectedView];
}
<强>夫特强>
override func awakeFromNib() {
super.awakeFromNib()
let selectedView = UIView(frame: self.bounds)
selectedView.backgroundColor = .green
self.selectedBackgroundView = selectedView
}
或者您可以直接从ViewController
collectionView:cellForItemAt
方法
<强> UPD 强>
正如Yerkebulan Abildin所提到的,只有从笔尖创建UICollectionViewCell
时,此代码才有效。如果您是通过代码创建的,则可以在selectedBackgroundView
方法中定义init
(因为awakeFromNib
不会打电话)