I have a collectionview controller and a collectionviewcell. FOr the collectionviewcell I have a custom class. I am trying to set the uiimage and it isn't working.
Thank you in advance!.
Method in collectionview controller where I am trying to set the image.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier=#"Cell";
CollectionVIewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
;
CollectionVIewCell *feederCell = (CollectionVIewCell*)[_availableFilters objectAtIndex:indexPath.row];
cell.labelDisplay.text=feederCell.filterName;
NSLog(#"selected =%#",cell.labelDisplay.text);
if (feederCell.isSelected) {
UIImageView *imageView=[[UIImageView alloc]init];
//process string name
NSString*filePath =[NSString stringWithFormat:#"%#.png",feederCell.filterName];
NSArray* words = [filePath componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceCharacterSet]];
filePath=[words componentsJoinedByString:#""];
cell.FilePath=filePath;
//image
UIImage *image = [UIImage imageNamed:filePath];
[imageView setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
[imageView setImage:image];
[cell setIconDisplay:imageView];//setting the image that won't set
}else if(!feederCell.isSelected){
UIImageView *imageView=[[UIImageView alloc]init];
NSString*filePath =[NSString stringWithFormat:#"%#.png",feederCell.filterName];
NSArray* words = [filePath componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceCharacterSet]];
filePath=[words componentsJoinedByString:#""];
UIImage *image = [UIImage imageNamed:filePath];
[imageView setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
[imageView setImage:image];
[cell setIconDisplay:imageView];
}
return cell;
.h file
//
// CollectionVIewCell.h
#import <UIKit/UIKit.h>
#interface CollectionVIewCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *IconDisplay;
#property (strong, nonatomic) IBOutlet UILabel *labelDisplay;
#property (assign,nonatomic) BOOL isSelected;
#property (strong,nonatomic)NSString*textName;
#property(strong,nonatomic)NSString*FilePath;
#end
.m file
//
// CollectionVIewCell.m
#import "CollectionVIewCell.h"
#implementation CollectionVIewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_labelDisplay.text=_textName;
_IconDisplay=[[UIImageView alloc]init];
}
return self;
}
#end
You need to add the UIImageView as a subview. Otherwise it exists but isn't displayed.
Related
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[_keyboard.collectionView registerClass:[NibCell class] forCellWithReuseIdentifier:#"Cell"];
static NSString *identifier = #"Cell";
NibCell *cell = [self.keyboard.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView * rampageGifImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, cell.frame.size.width, cell.frame.size.height)];
[rampageGifImage setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#.gif",[rampageGif objectAtIndex:indexPath.row]]]];
[cell.layer setCornerRadius:4];
[cell addSubview:rampageGifImage];
return cell;
}
You can use Gif Image by Adding SDWebImage from Github in your project.
Try like this,
#import "UIImage+GIF.h"
_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:#"YOURGIF_IMAGE"];
Hope this will help you.
Try it. It is small category that could loads animated GIF. Also, jpg, png, etc..
#import "ViewController.h"
#import "UIImage+Gif.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *imageView1;
#property (weak, nonatomic) IBOutlet UIImageView *imageView2;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Usage 1 : gifWidthData
NSData *data = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:#"f1" withExtension:#"gif"]];
self.imageView1.image = [UIImage gifWithData:data];
// Usage 2 : gifWidthURL
NSURL *url = [[NSBundle mainBundle] URLForResource:#"f2" withExtension:#"gif"];
self.imageView2.image = [UIImage gifWithURL:url];
}
I've been trying to configure a custom UICollectionViewCell that is supposed to present a UIView consisting of a few subviews generated with a custom method.
The problem is that when I try to pass the needed data from -cellForItemAtIndexPath to the cell's properties (NSStrings) the app crashes and the data doesn't seem to be passed at all, because NSLog returns (null) for all of the properties.
I thought that the problem was with the properties not being initialized, but when I initialized them in -initWithFrame, they didn't return any values. I tried to use the -initWithCoder and -awakeFromNib and it didn't work.
I also tried to utilize a custom method that would set the properties for me. While it seems to be working, I can't seem to find a way to add the generated view to the cell's view, as using [self.contentView addSubview:...] seems to be adding every generated view to every cell in the Collection View.
If you guys could help me out, I would be much grateful - I've spent my entire day on this, and I just can't get it to work. Perhaps I should do it differently?
My custom collection view cell's .h file:
#import "SHDesignChicago.h"
#interface SHDesignChicagoCollectionViewCell : UICollectionViewCell
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSString *date;
#property (strong, nonatomic) NSString *going;
#property (strong, nonatomic) PFFile *background;
#property (strong, nonatomic) UIView *generatedDesign;
- (void)setCellWithEventName:(NSString *)name eventDate:(NSString *)date eventGoing:(NSString *)going eventBackground:(PFFile *)background;
#end
And my custom collection view cell's .m file:
#import "SHDesignChicagoCollectionViewCell.h"
#implementation SHDesignChicagoCollectionViewCell
- (void)setCellWithEventName:(NSString *)name eventDate:(NSString *)date eventGoing:(NSString *)going eventBackground:(PFFile *)background {
UIImage *backgroundImage = [[UIImage alloc] initWithData:[background getData]];
NSLog(#"Event details:\nName: %#\nDate: %#\nGoing: %#\nBackground: %#", name, date, going, background);
self.generatedDesign = [SHDesignChicago designWithName:name date:date going:going background:backgroundImage frame:self.frame];
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//self.autoresizesSubviews = YES;
__block UIImage *backgroundImage;
[self.background getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) backgroundImage = [[UIImage alloc] initWithData:data];
}];
NSLog(#"Event details:\nName: %#\nDate: %#\nGoing: %#\nBackground: %#", self.name, self.date, self.going, self.background);
if (self.name != nil) {
UIView *generatedDesign = [SHDesignChicago designWithName:self.name date:self.date going:self.going background:backgroundImage frame:self.frame];
[self addSubview:generatedDesign];
}
}
return self;
}
#end
Also the cellForItemAtIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PFObject *event = [self.events objectAtIndex:indexPath.row];
NSString *name = event[#"eventName"];
NSDate *date = event[#"eventDate"];
PFFile *background = event[#"coverPhoto"];
if ([event[#"designId"] isEqual: #(1)]) {
// SHDesignChicago
SHDesignChicagoCollectionViewCell *chicagoCell = (SHDesignChicagoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"chicago" forIndexPath:indexPath];
/*
chicagoCell.name = #"TEST";
chicagoCell.date = #"TODAY, 5 PM";
chicagoCell.going = #"NATALIA KAWECKA AND 35 OTHERS ARE GOING";
chicagoCell.background = background;
*/
[chicagoCell setCellWithEventName:name eventDate:#"TODAY, 5 PM" eventGoing:#"NATALIA M AND 35 OTHERS ARE GOING" eventBackground:background];
return chicagoCell;
}
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
return cell;
}
I'm trying to add a "favorite button" to a custom cell in a UIableView.
The cell has a label and detailLabel that show fine. I must be doing something wrong but I can't figure out what it is. My code is below, and I changed my original method (commented) after studying this question.
My code is as follows:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyCustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
}
cell.nameLabel.text = [myMutableArray valueForKey:#"Name"];
cell.detailLabel.text = [myMutableArray valueForKey:#"Detail"];
if (isFavorite)
{
NSLog(#"fave");
UIImage *btnImage = [UIImage imageNamed:#"goldStar.png"];
[cell.favoriteButton setImage:btnImage forState:UIControlStateNormal];
//[cell.favoriteButton setImage:[UIImage imageNamed:#"yellowStar.png"] forState:UIControlStateNormal];
} else {
NSLog(#"out of fave");
UIImage *btnImage = [UIImage imageNamed:#"greyStar.png"];
[cell.favoriteButton setImage:btnImage forState:UIControlStateNormal];
//[cell.favoriteButton setImage:[UIImage imageNamed:#"greyStar.png"] forState:UIControlStateNormal];
}
return cell;
}
MyCustomCell.h
#interface MyCustomCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *nameLabel;
#property (nonatomic, weak) IBOutlet UILabel *detailLabel;
#property (nonatomic, strong) IBOutlet UIButton *favoriteButton;
MyCustomCell.m
#implementation MyCustomCell
#synthesize nameLabel = _nameLabel;
#synthesize detailLabel = _detailLabel;
#synthesize favoriteButton = _favoriteButton;
- (void)awakeFromNib {
_favoriteButton = [[DBTileButton alloc] init];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
I've checked and the button is hooked up ok in IB. Thanks ahead for any advice.
UPDATE I notice in the log message that the image frame is set at 0,0,0,0. I'm attaching a shot of the custom cell IB setup. Is something amiss there?
As far as I know IBOutlet for any sub classes of UIView shouldn't be strong! Anyway you no need to use IBOutlet, if you wanna initialize your button programmatically: at first, you forgot to set frame of your button and add it to cell view via addSubview. But it is easier way: just add button on storyboard, set custom class and remove this:
_favoriteButton = [[DBTileButton alloc] init];
EDIT: set class for your storyboard's button like on picture
Then change your outlet:
#property (nonatomic, weak) IBOutlet DBTileButton *favoriteButton;
And finally don't forget to connect outlet to your button and remove programmatically initializing.
To preface, I have some experience with iOS development, but this is my first app that I am going to publish to the AppStore, and also my first experience utilizing UICollectionView.
Here is a summary of what I am doing in my app:
I have a paged UICollectionView which contains several fullscreen UICollectionViewCells. Within each of these cells is another UICollectionView ('subCollectionView'), containing UICollectionViewCells ('subCollectionViewCells') which currently have their label set to "Test Text". When scrolling to the second collectionViewCell, the subCollectionViewCells of the first collectionViewCell are visible behind the second collectionViewCell's subCollectionView. I have linked the images to what is happening here.
The CollectionViewCell that includes the subCollectionView:
[VLCategoryCollectionViewCell.h]
#import <UIKit/UIKit.h>
#interface VLCategoryCollectionViewCell : UICollectionViewCell
#property (nonatomic, strong) NSString *imageName;
#property (strong, nonatomic) IBOutlet UIView *moduleSubview;
- (void)updateCell;
#end
[VLCategoryCollectionViewCell.m]
#import "VLCategoryCollectionViewCell.h"
#import "VLModuleViewController.h"
#interface VLCategoryCollectionViewCell()
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *categoryName;
#property (strong, nonatomic) VLModuleViewController *moduleViewController;
#end
#implementation VLCategoryCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle]
loadNibNamed:#"VLCategoryCollectionViewCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
-(void)updateCell {
_moduleViewController = [[VLModuleViewController alloc] initWithNibName:#"VLModuleViewController" bundle:nil];
_moduleViewController.view.frame = self.moduleSubview.bounds;
[self.moduleSubview addSubview:_moduleViewController.view];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Assets"];
NSString *filename = [NSString stringWithFormat:#"%#/%#", sourcePath, self.imageName];
UIImage *image = [UIImage imageWithContentsOfFile:filename];
NSString *fileTitle = [[filename lastPathComponent] stringByDeletingPathExtension];
[self.categoryName setFont:[UIFont fontWithName:#"OpenSans-ExtraBold" size:72.0]];
[self.categoryName setText:fileTitle];
[self.imageView setImage:image];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}
#end
[VLModuleViewController.h]
#import <UIKit/UIKit.h>
#interface VLModuleViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
#end
[VLModuleViewController.m]
#import "VLModuleViewController.h"
#import "VLModuleCollectionViewCell.h"
#interface VLModuleViewController ()
#property (nonatomic, strong) IBOutlet UICollectionView *moduleView;
#property (nonatomic, strong) NSArray *moduleArray;
#property (nonatomic) int currentIndex;
#property (nonatomic) NSString *cellIdentifier;
#end
#implementation VLModuleViewController
- (void)loadView {
[super loadView];
NSArray *moduleArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:#"Module_Tests"];
NSMutableArray *moduleImageArray = [[NSMutableArray alloc] initWithCapacity:[moduleArray count]];
for (NSString *path in moduleArray) {
[moduleImageArray addObject:[UIImage imageWithContentsOfFile:path]];
}
self.moduleArray = [NSArray arrayWithArray:moduleArray];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupCollectionView];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.moduleView setPagingEnabled:YES];
[self.moduleView setCollectionViewLayout:flowLayout];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark UICollectionView methods
- (void)setupCollectionView {
[self.moduleView registerClass:[VLModuleCollectionViewCell class] forCellWithReuseIdentifier:#"VLModuleCollectionViewCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.moduleView setCollectionViewLayout:flowLayout];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.moduleArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
VLModuleCollectionViewCell *cell = (VLModuleCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"VLModuleCollectionViewCell" forIndexPath:indexPath];
cell.titleLabel.text = #"Module Title Goes Here";
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(235, 147);
}
#end
I had a similar issue with labels overwriting themselves in collectionView, try calling your updateCell method in awakeFromNib, this did the trick for me.
Hi in my app i have to load images to UITableViewCell .which are coming from the server.so the problem is when ever i scroll the tableview images are loading every time and its loading lazy so i tried to stop reusing cells but its not working ,How to stop reusing the cells in UITableView.
my code is
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
RestaurantCustomCell *cell =(RestaurantCustomCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *topLevelObjects ;
topLevelObjects= [[NSArray alloc]init];
if(cell==nil)
{
topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RestaurantCustomCell" owner:self options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (RestaurantCustomCell *) currentObject;
break;
}
}
}
NSDictionary *dict=[restauarantsArr objectAtIndex:indexPath.row];
NSString *imgStr=[dict valueForKey:#"Img"];
[self processImageDataWithURLString:imgStr andBlock:^(NSData *imageData) {
if (self.view.window)
{
UIImage *img = [UIImage imageWithData:imageData];
if(img!=nil)
{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[img drawInRect:CGRectMake(0,0,100,100)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
cell.restaurantImg.image=newImage;
UIGraphicsEndImageContext();
}
}
}];
cell.nameLbl.text=[dict valueForKey:#"Restaurants"];
cell.typeLbl.text=[dict valueForKey:#"Rest_Cuisine"];
cell.timingsLbl.text=[dict valueForKey:#"Rest_Timings"];
cell.categoryLbl.text=[dict valueForKey:#"Rest_Category"];
cell.addressLbl.text=[dict valueForKey:#"Address"];
return cell;
}
You can not doing this in default table view cell. If you want to create this kind of things then you need to create custom tableview cell anbd do it what you want.
You have to make a custom cell like that:
RestaurantCustomCell.h
#import <UIKit/UIKit.h>
#interface RestaurantCustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *nameLbl;
#property (weak, nonatomic) IBOutlet UILabel *typeLbl;
#property (weak, nonatomic) IBOutlet UILabel *timingsLbl;
#property (weak, nonatomic) IBOutlet UILabel *categoryLbl;
#property (weak, nonatomic) IBOutlet UILabel *addressLbl;
#property (weak, nonatomic) IBOutlet UIImageView *restauranImg;
#end
RestaurantCustomCell.m
#import "RestaurantCustomCell.h"
#implementation RestaurantCustomCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)prepareForReuse{
self.nameLbl.text = #"";
self.typeLbl.text = #"";
self.timingsLbl.text = #"";
self.categoryLbl.text = #"";
self.addressLbl.text = #"";
}
#end
after in IB you add a new UITableViewCell at your UITableView and the class of it with you new custom cell set the Identify ID like "RestaurantCustomCell" add your labels and imageView to your custom cell and connect the Outlet, then you modify you tableView:cellForRowAtIndexPath: like that:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"RestaurantCustomCell";
RestaurantCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *dict=[restauarantsArr objectAtIndex:indexPath.row];
NSString *imgStr=[dict valueForKey:#"Img"];
[self processImageDataWithURLString:imgStr andBlock:^(NSData *imageData) {
if (self.view.window)
{
UIImage *img = [UIImage imageWithData:imageData];
if(img!=nil)
{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[img drawInRect:CGRectMake(0,0,100,100)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
cell.restaurantImg.image=newImage;
UIGraphicsEndImageContext();
}
}
}];
cell.nameLbl.text=[dict valueForKey:#"Restaurants"];
cell.typeLbl.text=[dict valueForKey:#"Rest_Cuisine"];
cell.timingsLbl.text=[dict valueForKey:#"Rest_Timings"];
cell.categoryLbl.text=[dict valueForKey:#"Rest_Category"];
cell.addressLbl.text=[dict valueForKey:#"Address"];
return cell;