gpt4 book ai didi

ios - 在自定义方法中访问 UICollectionViewCell 组件

转载 作者:行者123 更新时间:2023-11-29 01:42:39 24 4
gpt4 key购买 nike

我在 UICollectionViewCell 中有一些组件,我可以访问 cellForItemAtIndexPath 中的所有组件。我需要在自定义方法中访问组件,

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// UIButton
cell.btn1.frame =CGRectMake(380,100, 150, 40);
[cell.btn1 addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
return cell;
}

在自定义方法中,

-(void)btnClicked{
MycollectionclassView *cell =[[MycollectionclassView alloc]init];
cell.btn1.backgroundColor =[UIColor greenColor];
}

这里我不能改变按钮的颜色。

最佳答案

您必须创建协议(protocol)并为方法创建 IBAction。当您的操作方法被调用时,您可以通知协议(protocol),其具有 UICollectionView 协议(protocol)的屏幕将接收此事件。

在单元头文件.h 中定义协议(protocol):

@protocol YourCellNamelDelegate <NSObject>

@required
/**
* Notifies that current ITEM was clicked on icon.
*
* @param cell The current cell that was clicked.
*/
-(void)bookmarkClicked:(YourCellName *)cell; // OR without argument


@interface YourCellName : UITableViewCell

/**
* Reference to 'YourCellNameDelegate' delegate.
*/
@property (assign,nonatomic) id<YourCellNamelDelegate>delegate;

...

在您的手机文件中。m

...

- (IBAction)bookmarkClickAction:(id)sender {

// change or update screen element here ...

if (self.delegate) {
[self.delegate bookmarkClicked:self];
}

}

在您的 ViewController 上实现您的协议(protocol)

@interface SMGListViewController () <YourCellNameDelegate>


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

// get your cell here, for example in my case:

SMGCityGuideCollectionViewCell *cell;
cell = (SMGCityGuideCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

SMGTouristInfo *touristInfo = [self.listTouristInfo objectAtIndex:indexPath.row];
[cell setTouristInfoCell:touristInfo];

// IMPORTANT HERE *************************
cell.delegate = self;
// IMPORTANT HERE *************************

return cell;
}
...


#pragma mark <SMGPlaceCellDelegate>

-(void)bookmarkClicked:(SMGPlaceCell *)cell {

// notify events here ...

NSIndexPath *index = [self.tableViewPlaces indexPathForCell:cell];
[self.tableViewPlaces reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
}

希望对您有帮助! :)

关于ios - 在自定义方法中访问 UICollectionViewCell 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com