change cell imageView in uicollectionview didSelectItemAtIndexPath method - uiimageview

I built a CollectionView controller with fixed imageView in 4 cells.
I'd like the imageView to change on cell selection.
Could you help me with this one?
Thank you
here's my code
CollectionView controller .m
....
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return 4;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Cell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
UIImage *image;
int row = [indexPath row];
image = [UIImage imageNamed:#"ICUbedGREEN.png"];
myCell.imageView.image = image;
return myCell;
}
I'd like the image to change on press but I cannot figure it out...
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath
{
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"ICUbedRED.png"]];
cell.imageView.image = .....
NSLog(#"elementselected");
}

in your subclass for UICollectionViewCell implement the KVO listening method. Make sure you set multiselection to true if you want it to be deselected.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString#"selected"])
{
// check value of self.selected to know what you are currently.
// change picture of image here
}
}
in your cells init method you will need to add yourself as a listener so
[self addObserver:self forKeyPath:#"selected" options:nil context:nil];

It can be most stupid answer to your questions but it worked for me. I dont know how to work with KEy value paths as stated by Samuel.
Basically i made a NSMutableArray to store the status of icons, red or green..YES or NO..
selState = [[NSMutableArray alloc] initWithObjects:#"NO",#"NO",#"NO",#"NO",nil ];
and then in "ItemForIndexPath" method, checked the value to set image for that item
if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"NO"]) {
image = [UIImage imageNamed:#"ICUbedGREEN.png"];
}
else
{
image = [UIImage imageNamed:#"ICUbedRED.jpg"];
}
When item is selected, using IndexPath, altered the value of NO into YES or vice versa..
if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"NO"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:#"YES"];
}
else if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"YES"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:#"NO"];
}
And then updated the collection View
[self.collectionView reloadData];
ALL CODE HERE
#interface ViewController (){
NSMutableArray *selState;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
selState = [[NSMutableArray alloc] initWithObjects:#"NO",#"NO",#"NO",#"NO",nil ];
}
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return 4;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Cell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
UIImage *image;
if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"NO"]) {
image = [UIImage imageNamed:#"ICUbedGREEN.png"];
}
else
{
image = [UIImage imageNamed:#"ICUbedRED.jpg"];
}
myCell.imageView.image = image;
return myCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath
{
if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"NO"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:#"YES"];
}
else if ([[selState objectAtIndex:indexPath.row] isEqualToString:#"YES"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:#"NO"];
}
[self.collectionView reloadData];
}
#end
Thanks
EDITING---->>
the above code in ItemForIndexPath can also be written in
image = [[selState objectAtIndex:indexPath.row] isEqualToString:#"NO"] ?
[UIImage imageNamed:#"ICUbedGREEN.png"] : [UIImage imageNamed:#"ICUbedRED.jpg"];
END EDITING

Related

Link a search bar cell label to view controller

I am trying to create a search bar in Xcode so when you search for an item, you can click on the search result cell and it will go to a view controller but all it is doing now is going to the sea view controller and just displaying the label of the cell i clicked on.
Here is my .m file
#interface ListTableViewController () <UISearchDisplayDelegate>
#property (strong, nonatomic) NSArray *dataArray;
#property (strong, nonatomic) NSArray *searchResults;
#end
#implementation ListTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataArray = [NSArray arrayWithObjects:#"Tomb Raider", #"Little Big Planet", #"Unchanted 3", #"BlackOps 2", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)filterContentForSearchText: (NSString *) searchText
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF CONTAINS[cd] %#", searchText];
self.searchResults = [self.dataArray filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString];
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
if (tableView == self.tableView) {
return [self.dataArray count];
} else { // (tableView == self.searchDisplayController.searchResultsTableView)
return [self.searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (tableView == self.tableView) {
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - Table view delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showDetails"]) {
DetailsViewController *dvc = segue.destinationViewController;
NSIndexPath *indexPath = nil;
if ([self.searchDisplayController isActive]) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
dvc.sendLabel = [self.searchResults objectAtIndex:indexPath.row];
return;
} else{
indexPath = [self.tableView indexPathForSelectedRow];
dvc.sendLabel = [self.dataArray objectAtIndex:indexPath.row];
return;
}
}
}
#end
Thanks, anything will help.
You must implement this delegate method :
// Method returns the clicked row.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
YourPushedViewController *ypVC = [[YourPushedViewController alloc] initWithNibName:#"YourPushedViewController" bundle:nil];
ypVC.selectedText = myResultArray[indexPath.row];
[self.navigationController pushViewController:ypVC animated:YES];
}
That method is response for selecting row and passing selected result to another view.
This is hint for you :Passing Data between View Controllers

UITableView Segue

Im trying to make a small project. Could someone help me understand why the segue does not work?
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarDetailViewController.h"
#interface CarTableViewController ()
#end
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.carMakes = [[NSArray alloc]
initWithObjects:#"Chevy",
#"BMW",
#"Toyota",
#"Volvo",
#"Smart", nil];
self.carModels = [[NSArray alloc]
initWithObjects:#"Volt",
#"Mini",
#"Venza",
#"S60",
#"Fortwo", nil];
self.carImages = [[NSArray alloc]
initWithObjects:#"chevy_volt.jpg",
#"mini_clubman.jpg",
#"toyota_venza.jpg",
#"volvo_s60.jpg",
#"smart_fortwo.jpg", nil];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _carModels.count;
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [self.carMakes
objectAtIndex: [indexPath row]];
cell.modelLabel.text = [self.carModels
objectAtIndex:[indexPath row]];
UIImage *carPhoto = [UIImage imageNamed:
[self.carImages objectAtIndex: [indexPath row]]];
cell.carImage.image = carPhoto;
return cell;
}
The code work´s fine, and loads a tableView, but I need to go to CarDetailViewControler and I´m using the following code, but it does not work.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController =
[segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView
indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects: [self.carMakes
objectAtIndex:[myIndexPath row]],
[self.carModels objectAtIndex:[myIndexPath row]],
[self.carImages objectAtIndex:[myIndexPath row]],
nil];
}
}
In the storyboard did you use a cell prototype? If so, did you control-drag from the prototype to the destination viewcontroller and create the named segue?
The method you are using requires the segue to be defined completely in the storyboard, meaning the trigger for the segue is tied to the cell prototype.
You can manually trigger a segue using:
[self performSegueWithIdentifier:#"ShowCarDetails" sender:self];
in your:
tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath as an alternative.

CustomCell in XCode not displaying value

I created a custom cell in table view that has a search bar. Text entered by users will be used to search a SQLite db and results displayed in table view. The problem I have now is that the search result is not displayed in the table view if I use custom cell but works when I use the default cell. For e.g., in code below, if I use [cell setText:currentSubLocality]; it will display the result but it will not display result if I use cell.lblG.text = currentLocation;. Please help, been struggling with it for 2 days. Thanks
#import "CustomViewController.h"
#import "FMDBDataAccess.h"
#import "locationCode.h"
#import "CustomCell.h"
#interface CustomViewController ()
#end
#implementation CustomViewController{
NSMutableArray *searchResults;}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [searchResults count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"vvv"];
if (cell==nil){
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"vvv"];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
locationCode *code = [[locationCode alloc] init];
code= [searchResults objectAtIndex:indexPath.row];
NSString *currentLocation = code.location;
NSString *currentSubLocality = code.subLocality
//[cell setText:currentSubLocality];
cell.lblG.text = currentLocation;
cell.lblL.text = currentSubLocality;
}
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSString *databasePath = [[NSBundle mainBundle] pathForResource:#"spr" ofType:#"sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:databasePath];
[database open];
searchResults = [[NSMutableArray alloc] initWithObjects:nil count:0];
NSString *query = [NSString stringWithFormat:#"select * from Locations where locationCode like '%#%%'", searchText];
FMResultSet *results = [database executeQuery:query];
while([results next]) {
locationCode *code = [[locationCode alloc] init];
code.code = [results stringForColumn:#"locationcode"];
code.subLocality= [results stringForColumn:#"sublocality"];
code.longitude= [results stringForColumn:#"longitude"];
code.latitude= [results stringForColumn:#"latitude"];
[searchResults addObject:code];
}
[database close];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#end
Try This it will work. paste the below code in cellforrowatindexpath method and don't forget to set your TableViewCell "Identifier" in your Attribute inspector
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
I solved the problem by adding the tableview as an outlet. Then change the following line
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"vvv"];
to
CustomCell *cell = [customTableView dequeueReusableCellWithIdentifier:#"vvv"];

initWithStyle:UITableViewCellStyleSubtitle but subtitle not showing

Am trying to run the following code for a table with initWithStyle:UITableViewCellStyleSubtitle but the subtitle is not showing. Can you tell me what's wrong?
Thanks in advance!
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize listData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *array = [[NSArray alloc] initWithObjects:#"Sleepy", #"Sneezy", #"Bashful", #"Happy", #"Doc", #"Grumpy", #"Dopey", #"Thorin", #"Dorin", #"Nori", #"Ori", #"Balin", #"Dwalin", #"Fili", #"Kili", #"Oin", #"Gloin", #"Bifur", #"Bofur", #"Bombur", nil];
self.listData = array;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.listData = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIdentifier];
}
UIImage *image = [UIImage imageNamed:#"star.png"];
cell.imageView.image = image;
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
if (row < 7)
cell.detailTextLabel.text = #"Mr. Disney";
else
cell.detailTextLabel.text = #"Mr.Tolkien";
}
#end
return cell;
Should be the last line. It returns before setting the detailTextLabel's text property.
Also, you should have received a warning from Xcode about "unreachable code."

How to solve slow scrolling in UITableView - using the YouTube API

I'm working with the google YouTube API, and I'm using this code found here http://pastebin.com/vmV2c0HT
The Code that slows things down is this one here
cell.imageView.image = [UIImage imageWithData:data];
When I remove that code it scrolls smoothly. Any idea on how I can go about having it load the images from google but still scroll smoothly? I've read some of the answers on loading images in a different way, but I still can't figure out how I'll make that work with the code I'm using.
Any help will be appreciated.
Bellow is the full code.
#import "RootViewController.h"
#interface RootViewController (PrivateMethods)
- (GDataServiceGoogleYouTube *)youTubeService;
#end
#implementation RootViewController
#synthesize feed;
- (void)viewDidLoad {
NSLog(#"loading");
GDataServiceGoogleYouTube *service = [self youTubeService];
NSString *uploadsID = kGDataYouTubeUserFeedIDUploads;
NSURL *feedURL = [GDataServiceGoogleYouTube youTubeURLForUserID:#"BmcCarmen"
userFeedID:uploadsID];
[service fetchFeedWithURL:feedURL
delegate:self
didFinishSelector:#selector(request:finishedWithFeed:error:)];
[super viewDidLoad];
}
- (void)request:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedBase *)aFeed
error:(NSError *)error {
self.feed = (GDataFeedYouTubeVideo *)aFeed;
[self.tableView reloadData];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[feed entries] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0f;
}
- (void)dealloc {
[super dealloc];
}
- (GDataServiceGoogleYouTube *)youTubeService {
static GDataServiceGoogleYouTube* _service = nil;
if (!_service) {
_service = [[GDataServiceGoogleYouTube alloc] init];
[_service setShouldCacheDatedData:YES];
[_service setServiceShouldFollowNextLinks:YES];
}
// fetch unauthenticated
[_service setUserCredentialsWithUsername:nil
password:nil];
return _service;
}
#end
GCD is a wonderful thing. Here is what I do:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"youTubeCell";
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
// Load the image with an GCD block executed in another thread
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage * image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell setNeedsLayout];
});
});
dispatch_release(downloadQueue);
return cell;
}
Scrolling is now super smooth. The only drawback is that when you scroll quickly, cells are re-used and sometimes the images change as new ones come in.

Resources