简体   繁体   中英

Xcode - How to call method from another class

my first class .h :

@interface CollectionViewController : UICollectionViewController <..>

  @property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

  -(void)refreshView;

@end

my first class .m

@implementation CollectionViewController

  -(void)refreshView
  {
      [self.collectionView reloadData];
  }

@end

i need to call this method from my second class

my second class .h

@interface CollectionViewCell : UICollectionViewCell

   - (IBAction)buttonAction:(id)sender;

@end

my second class .m

@implementation CollectionViewCell

  - (IBAction)myButtonAction:(id)sender {

  //i need to call the method "refreshView" here

  }

@end

I tried to edit the method refreshView from private to public but it's not compatible with " [self.collectionView reloadData]; "

Thanks for help.

It's not a good idea to have your cell "know about" its collection view.

Use delegation instead...

CollectionViewCell.h

@protocol CollectionViewCellDelegate <NSObject>
- (void)refreshButtonPressedForCell:(CollectionViewCell *)cell;
@end

@interface CollectionViewCell : UICollectionViewCell
@property (nonatomic, weak) id<CollectionViewCellDelegate> delegate;
@end

CollectionViewController.m

@interface CollectionViewController : UICollectionViewController <CollectionViewCellDelegate>
@end

@implementation CollectionViewController

- (void)refreshButtonPressedForCell:(CollectionViewCell *)cell {
    [self.collectionView reloadData];
}

@end

Don't forget to set the delegate property on each of your cells!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM