I have a tableView which I get the content from Parse.com (an image, one title and one description) and I am using a UIView for my detailView. When a cell is tapped UIView comes in with an animation. I managed to get My title and description of events but I couldn't get the Image file.
How to pass the parsed image into the UIView?
Thanks.
Here is my .h file
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "TableCell.h"
#interface ViewController : UIViewController <UITableViewDelegate> {
NSArray *events;
}
#property (weak, nonatomic) IBOutlet UITableView *newsTable;
#property (strong, nonatomic) IBOutlet UIView *detailView;
#property (strong, nonatomic) IBOutlet UILabel *InfoDetailLabel;
- (IBAction)backBtn:(id)sender;
#property (strong, nonatomic) IBOutlet UILabel *viewTitle;
Here is the .m file
#import "ViewController.h"
#import "TableCell.h"
#import "Reachability.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize newsTable;
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Pull to refresh
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.newsTable addSubview:refreshControl];
//Checking connection
if (![self connected])
{
// not connected
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Internet Connection Not Found" message:#"Please check your network settings!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
} else
{
// connected, do some internet stuff
}
// Do any additional setup after loading the view, typically from a nib.
[self performSelector: #selector(retreiveFromParse)];
}
//pull to refresh
- (void)refresh:(UIRefreshControl *)refreshControl {
[refreshControl endRefreshing];
}
- (void) retreiveFromParse {
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"News"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
events = [[NSArray alloc] initWithArray:objects];
}
[newsTable reloadData];
}];
}
//*********************Setup table of folder names ************************
//get number of sections in tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
//get number of rows by counting number of folders
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return events.count;
}
//setup cells in tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//setup cell
static NSString *CellIdentifier = #"EventCell";
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
PFObject *tempObject = [events objectAtIndex:indexPath.row];
cell.TitleLabel.text = [tempObject objectForKey:#"Event"];
cell.DescriptionLabel.text = [tempObject objectForKey:#"Description"];
// To get the image file from Parse class
PFFile *imageFile = [tempObject objectForKey:#"imageFile"];
PFImageView *imageView = [[PFImageView alloc] init];
imageView.file = imageFile;
[imageView loadInBackground:^(UIImage *img,NSError *error){
if(!error)
{
UIImageView *yourImageView = [[UIImageView alloc] init];
yourImageView.image = imageView.image;
/*OR*/
cell.imageView.image = imageView.image;
}}];
return cell;
}
//user selects folder to add tag to
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cell tapped");
//For detail view
PFObject *tempObject = [ events objectAtIndex:indexPath.row];
NSLog(#"%#", tempObject.objectId);
_InfoDetailLabel.text = [tempObject objectForKey:#"detailinformation"];
[self animateDetailView];
_viewTitle.text = [tempObject objectForKey:#"Event"];
[self animateDetailView];
}
//for animation of detailview
- (void) animateDetailView {
[UIView animateWithDuration:0.3 animations:^{
_detailView.frame = CGRectMake(0, 0, 320, 518);
}];
}
//back button with animation
- (IBAction)backBtn:(id)sender {
[UIView animateWithDuration:0.3 animations:^{
_detailView.frame = CGRectMake(320, 0, 320, 518);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
and my cell .h
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#interface TableCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *TitleLabel;
#property (strong, nonatomic) IBOutlet UILabel *DescriptionLabel;
#property (strong, nonatomic) IBOutlet PFImageView *imageView;
#end
Try,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"cell tapped");
//Assuming not reordering the cells after it loaded
TableCell *cell = (TableCell *)[tableView cellForRowAtIndexPath:indexPath];
[[yourDetailView imageView] setImage:[[cell imageView] image]];
.....
}
or you can use the same method loadInBackground: used in cellForRow in detailView also
Related
i already passed input text with prepareForSegue, text into mutablearray, then passing that array with prepareforeSegue to second VC with tableview so table cell now displays name. But what with selected/picked image in uIImageView in first vc so table cell in second VC can display image in a row next to name? i manage to do it with image from imagexxassets i followed the same logic like passing text but keep failing.
VIewController.h
#import <UIKit/UIKit.h>
#import "TableViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
#property (strong, nonatomic) IBOutlet UITextField *inputName;
#property (nonatomic) NSMutableArray *items;
//#property (nonatomic) NSMutableArray *images;
- (IBAction)AddData:(id)sender;
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UIButton *selectPhoto;
#property (strong, nonatomic) IBOutlet UIButton *takePhotoFromCamera;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_items = [[NSMutableArray alloc]init];
//_images = [[NSMutableArray alloc]init];
[self.takePhotoFromCamera addTarget:self action:#selector(_takePhoto) forControlEvents:UIControlEventTouchUpInside];
[self.selectPhoto addTarget:self action:#selector(_selectPhoto) forControlEvents:UIControlEventTouchUpInside];}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)AddData:(id)sender
{
//[_images addObject:self.imageView.image];
//[_images insertObject:self.imageView.image atIndex:0];
if ([self.inputName.text length]> 0)
{
[_items addObject:self.inputName.text];
//[_images addObject:self.imageView.image];
[self performSegueWithIdentifier:#"tableSegue" sender:self];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error"
message:#"You must enter some data"
delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (void)addItemViewController:(TableViewController *)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag{
NSLog(#"DATA=%#", item);
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"tableSegue"])
{
TableViewController *controller = (TableViewController *)segue.destinationViewController;
controller.items = _items;
//TableViewController *controller1 = (TableViewController *)segue.destinationViewController;
//controller1.images = _images;
NSLog(#"%#",self.inputName.text);
self.inputName.text = NULL;
}
}
#pragma mark code for images
-(void)_takePhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)_selectPhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:NO completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
}
}
-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
TableViewController.h
#import <UIKit/UIKit.h>
//using delegate
#protocol TableViewControllerDelegate <NSObject>
- (void)addItemViewController:(id)controller didFinishSelectingItem:(NSMutableArray *)item selectedTag:(int)tag;
#end
//extra attention here
#interface TableViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
// id of delegate
#property (nonatomic, weak) id <TableViewControllerDelegate> delegate;
#property (nonatomic) NSMutableArray *items;
//#property (nonatomic) NSMutableArray *images;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
TableViewController.m
#import "TableViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// code for reversing objects in array so tableview can put new rows on top
//_items = [[[_items reverseObjectEnumerator] allObjects] mutableCopy];
self.tableView.delegate = self;
self.tableView.dataSource = self;
// setting invisible footer to display only rows which contains data and to remove border lines in tableview
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 10.0f)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:#"BasicCell" forIndexPath:indexPath];
//NSString *lijevaSlika = [NSString stringWithFormat:#"dice%i", sum];
//[questionTexts objectAtIndex:0]
//NSString *selectedImage = [NSString stringWithFormat:_images];
myCell.imageView.image = [UIImage imageNamed:#"2.png"];
myCell.textLabel.text = _items[indexPath.row]; //name of objects in array are displayed in cells
myCell.textLabel.textColor = [UIColor blueColor]; //changing color of text in cell
//changing background of cell
/*myCell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"back.png"]];
myCell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"front.png"]];
*/
return myCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count]; //objects in arrays - rows in table
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[_items removeObjectAtIndex:indexPath.row]; //swipe to left do delete row
[self.tableView reloadData];
}
/*- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//selected row returns to previous viewcontroller
[self.navigationController popViewControllerAnimated:YES];
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
First you have to store selected images in array then you have to pass that array in same way you are passing _items array.Then In cellForRowAtIndexPath of TableViewController add this line and check you are getting anything in _images array
myCell.imageView.image = [_images objectAtIndex:indexPath.row];
I have my UITableView displaying JSON info being returned from a cloud code function. For some reason, it correctly displays the titles of the items being returned, but I can't get it to display the price as a subtitle of each cell. Setting the style as UITableViewCellStyleSubtitle doesn't seem to work, and gives me a warning stating Implicit conversion from enumeration type 'enum UITableviewCellStyle' to different enumeration type.
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// _matchCenter.dataSource = self;
// _matchCenter.delegate = self;
// [self.view addSubview:self.matchCenter];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-200);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
self.matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenterTest"
withParameters:#{
#"test": #"Hi",
}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
self.matchCenterArray = [result objectForKey:#"Top 3"];
dispatch_async(dispatch_get_main_queue(), ^{
[_matchCenter reloadData];
});
NSLog(#"Test Result: '%#'", result);
}
}];
[self.matchCenter registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.matchCenterArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *matchCenterDictionary= [self.matchCenterArray objectAtIndex:indexPath.row];
cell.textLabel.text = [matchCenterDictionary objectForKey:#"Title"];// title of the item
cell.detailTextLabel.text = [matchCenterDictionary objectForKey:#"Price"];// price of the item
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The cell you have registered is a default styled UITableViewCell, it does not have a subTitle. You can't change the style of the cell once it's created.
You basically have two options:
create a simple UITableViewCell subclass that uses UITableViewCellStyleSubtitle (or any other style of your choice)
#interface MyTableViewCell : UITableViewCell
#end
#implementation MyTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
// overwrite style
self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
return self;
}
#end
...
[self.matchCenter registerClass:[MyTableViewCell class] forCellReuseIdentifier:#"Cell"];
Or return to the old style dequeue technique where you create a cell if none could be dequeued
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
/* configure */
}
If you do this, you have to remove the registerClass:forCellReuseIdentifier: call.
I would go with option one, because most likely pretty soon you will figure out that the built in cells are very limited and you want to add your own views (e.g. labels, image views). And if you use a subclass you can use properties to access those views, and don't have to use hacks like tags to access them.
In Table View subtitle is not present otherwise you customize your cell
use detail text label
cell.detailTextLabel.text = [array objectForKey:#"Value"];
Please bear with me, I am just starting iOS development. I am trying to display a custom tableViewCell within a storyboard tableView. I have done the following.
I have created a new .xib with a tableViewCell in it
I have then created a custom class for this. the .h file looks like this
#import <UIKit/UIKit.h>
#interface CustomTableCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *thumbnailImageView;
#property (weak, nonatomic) IBOutlet UILabel› *titleLabel;
#end
Then in my TableViewController.m I have imported the CustomTableCell.h and I am doing following for 10 rows
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.titleLabel.text ="test text";
return cell;
}
This seems fine to build, but when the project loads nothing happens. Any advice will be great.
I have placed a breakpoint in the cellForRowAtIndexPath method, however it never reaches this point. here is a screen shot of the simulator
You must register your .xib file. In your viewDidLoad method, add the following:
[self.tableView registerNib:[UINib nibWithNibName:#"CustomTableCell" bundle:nil]
forCellReuseIdentifier:#"CustomTableCell"];
The way you are loading the nib is really old-fashioned and outdated. It is much better (since iOS 6) to register the nib and use dequeueReusableCellWithIdentifier:forIndexPath:.
See my explanation of all four ways of getting a custom cell.
Ensure that the delegate and datasource are set in the storyboard for the UITableView. This will ensure that cellForRowAtIndexPath is getting called for each row. You can put an NSLog message in that method to verify the same thing.
Also, since you are using a storyboard, you may want to look into Prototype Cells for the UITableView. They are a much easier way of doing the same thing - creating a UITableView with custom cells.
Here's a decent tutorial on using Prototype cells within your storyboard's UITableView:
http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
- (void) viewDidLoad {
[super viewDidLoad];
UINib *cellNib = [UINib nibWithNibName:#"CustomTableCell" bundle:[NSBundle mainBundle]];
[self.tableView registerNib:cellNib forCellReuseIdentifier:#"CustomTableCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomTableCell";
CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text ="test text";
return cell;
}
A very basic question, but have you implemented the tableview delegate method that indicates how many cells should be displayed? The delegate method is the following:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//Return number of cells to display here
return 1;
}
Be sure to have only one item in your xib (Uitableviewcell instance)
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#import "NewViewController.h"
#import "CustomCellVC.h"
#interface FirstVC : UIViewController
{
DetailViewController *detailViewController;
NewViewController *objNewViewController;
CustomCellVC *objCustom;
NSMutableData *webData;
NSArray *resultArray;
//IBOutlet UIButton *objButton;
}
#property(strong,nonatomic)IBOutlet DetailViewController *detailViewController;
#property(strong,nonatomic)IBOutlet UITableView *objTable;
-(void)loginWS;
-(IBAction)NewFeatureButtonClk:(id)sender;
#end
#import "FirstVC.h"
#interface FirstVC ()
#end
#implementation FirstVC
#synthesize objTable;
#synthesize detailViewController;
- (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 from its nib.
objTable.frame = CGRectMake(0, 20, 320, 548);
[self loginWS];
}
-(void)loginWS
{
//Para username password
NSURL *url = [NSURL URLWithString:#"http://192.168.0.100/FeatureRequestComponent/FeatureRequestComponentAPI"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [req addValue:[NSString stringWithFormat:#"%i",postBody.length] forHTTPHeaderField:#"Content-Length"];
[req setTimeoutInterval:60.0 ];
//[req setHTTPBody:postBody];
//[cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"CellBg.png"]]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:req delegate:self];
if (connection)
{
webData = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
resultArray = [[NSArray alloc]initWithArray:[responseDict valueForKey:#"city"]];
NSLog(#"resultArray: %#",resultArray);
[self.objTable reloadData];
}
-(IBAction)NewFeatureButtonClk:(id)sender
{
objNewViewController=[[NewViewController alloc]initWithNibName:#"NewViewController" bundle:nil];
// Push the view controller.
[self.navigationController pushViewController:objNewViewController animated:YES];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [resultArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
objCustom = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (objCustom == nil) {
objCustom = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//objCustom.persnName.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Name"];
//objCustom.persnAge.text=[[resultArray objectAtIndex:indexPath.row]valueForKey:#"Age"];
// Configure the cell...
objCustom.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"FeatureTitle"];
objCustom.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:#"Description"];
return objCustom;
}
#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here, for example:
// Create the next view controller.
detailViewController = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.objData=[resultArray objectAtIndex:indexPath.row];
// Pass the selected object to the new view controller.
// Push the view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#import "DetailData.h"
#interface DetailViewController : UIViewController
{
DetailData *objData;
}
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#property(strong,nonatomic)IBOutlet DetailData *objData;
-(IBAction)voteBtnClk:(id)sender;
#end
#import "DetailViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
#synthesize objData,usecaseTF,featureTF,priority,voteBtn;
- (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 from its nib.
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
usecaseTF.text=objData.usecaseTF;
featureTF.text=objData.featureTF;
priority.text=objData.priority;
}
-(IBAction)voteBtnClk:(id)sender
{
if ([voteBtn.currentImage isEqual:#"BtnGreen.png"])
{
[voteBtn setImage:[UIImage imageNamed:#"BtnBlack.png"] forState:UIControlStateNormal];
}
else
{
[voteBtn setImage:[UIImage imageNamed:#"BtnGreen.png"] forState:UIControlStateNormal];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface NewViewController : UIViewController<UITextFieldDelegate>
{
UITextField *currentTF;
}
#property(strong,nonatomic) IBOutlet UITextField *nameTF;
#property(strong,nonatomic)IBOutlet UITextField *emailTF;
#property(strong,nonatomic)IBOutlet UITextField *featureTF;
#property(strong,nonatomic)IBOutlet UITextField *descpTF;
#property(strong,nonatomic)IBOutlet UITextView *UsecaseTV;
#property(strong,nonatomic)IBOutlet UIButton *HighBtn;
#property(strong,nonatomic)IBOutlet UIButton *LowBtn;
#property(strong,nonatomic)IBOutlet UIButton *MediumBtn;
-(IBAction)sendRequestBtnClk:(id)sender;
-(IBAction)RadioBtnHigh:(id)sender;
-(IBAction)RadioBtnLow:(id)sender;
-(IBAction)RadioBtnMedium:(id)sender;
-(void)radioBtnClick;
#end
#import "NewViewController.h"
#interface NewViewController ()
#end
#implementation NewViewController
#synthesize nameTF,emailTF,featureTF,descpTF,UsecaseTV,LowBtn,HighBtn,MediumBtn;
- (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 from its nib.
self.title=#"Did I Know This";
currentTF=[[UITextField alloc]init];
[ self radioBtnClick];
}
-(IBAction)sendRequestBtnClk:(id)sender
{
if (nameTF.text.length==0)
{
[self showAlertMessage:#"Please enter Your Name"];
// return NO;
}
else if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email ID"];
}
if (emailTF.text.length==0)
{
[self showAlertMessage:#"Please enter email address"];
}
else if ([self emailValidation:emailTF.text]==NO)
{
[self showAlertMessage:#"Please enter valid email address"];
}
else if(featureTF.text.length==0)
{
[self showAlertMessage:#"Please Confirm the Feature title"];
}
}
-(BOOL) emailValidation:(NSString *)emailTxt
{
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:emailTxt];
}
-(void)showAlertMessage:(NSString *)msg
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Note" message:msg delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
#pragma mark TextField Delegates
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[currentTF resignFirstResponder];
return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
currentTF = textField;
[self animateTextField:textField up:NO];
}
-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
int movementDistance = 0; // tweak as needed
if (textField.tag==103||textField.tag==104||textField.tag==105||textField.tag==106)
{
movementDistance = -130;
}
else if (textField.tag==107||textField.tag==108)
{
movementDistance = -230;
}
else
{
movementDistance = 00;
}
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? movementDistance : -movementDistance);
[UIView beginAnimations: #"animateTextField" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
-(void)radioBtnClick
{
if ([HighBtn.currentImage isEqual:#"radiobutton-checked.png"])
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
else
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
}
-(IBAction)RadioBtnHigh:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnLow:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
}
-(IBAction)RadioBtnMedium:(id)sender
{
[LowBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[HighBtn setImage:[UIImage imageNamed:#"radiobutton-unchecked.png"] forState:UIControlStateNormal];
[MediumBtn setImage:[UIImage imageNamed:#"radiobutton-checked.png"] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#interface CustomCellVC : UITableViewCell
#property (strong,nonatomic) IBOutlet UIImageView *persnImage;
#property (strong,nonatomic) IBOutlet UIButton *thumbImage;
#property (strong,nonatomic) IBOutlet UIImageView *calenderImage;
#property (strong,nonatomic) IBOutlet UIButton *voteImage;
#property (strong,nonatomic) IBOutlet UIButton *selectImage;
#property (strong,nonatomic) IBOutlet UILabel *publabel;
#property (strong,nonatomic) IBOutlet UILabel *IdLabel;
#property (strong,nonatomic) IBOutlet UILabel *decpLabel;
#property (strong,nonatomic) IBOutlet UITextField *ansTF;
#end
#import "CustomCellVC.h"
#implementation CustomCellVC
#synthesize ansTF,persnImage,publabel,thumbImage,calenderImage,voteImage,selectImage,IdLabel,decpLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
#synthesize ObjFirstVC,objNavc;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
ObjFirstVC=[[FirstVC alloc ]initWithNibName:#"FirstVC" bundle:nil];
objNavc=[[UINavigationController alloc]initWithRootViewController:ObjFirstVC];
[self.window addSubview:objNavc.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
#import <Foundation/Foundation.h>
#interface DetailData : NSObject
#property(strong,nonatomic)IBOutlet UITextField *usecaseTF;
#property(strong,nonatomic)IBOutlet UITextView *featureTF;
#property(strong,nonatomic)IBOutlet UILabel *priority;
#property(strong,nonatomic)IBOutlet UIButton *voteBtn;
#end
I have a project that displays a feed of statuses similar to other social networks. Each feed item has several button that do different things. 1 of the buttons opens a new viewcontroller that displays the comments that have been posted on a particular status. When this button is clicked and the view controller is opened i would like it to be a push segue so that their is a back button and the user can navigate back to the feed.
When this button is clicked and the new vc is launched some unique data about the particular status/cell being clicked needs to be sent to the "comments vc ". Where would the code for doing this go?
CUSTOM CELL .H
#import <UIKit/UIKit.h>
#interface FeedItemCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *DefaultImg;
#property (weak, nonatomic) IBOutlet UILabel *NameLabel;
#property (weak, nonatomic) IBOutlet UILabel *StatusLabel;
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#property (nonatomic, copy) NSString *msg_id;
#property (nonatomic, copy) NSString *status;
#property (nonatomic, weak) IBOutlet UIButton* commentButton;
#property (nonatomic, weak) IBOutlet UIButton* bumpButton;
#property (strong, nonatomic) id delegate;
-(IBAction)viewComments:(id)sender;
-(IBAction)bump:(id)sender;
#end
#protocol CustomCellProtocol <NSObject>
- (void)EBCellPressed:(NSString *)cellName;
CUSTOM CELL .M
#import "FeedItemCell.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface FeedItemCell() <WYPopoverControllerDelegate>
{
}
- (IBAction)open:(id)sender;
- (void)close:(id)sender;
#end
#implementation FeedItemCell
#synthesize commentButton;
- (instancetype)initWithDelegate:(id)delegate {
self = [super init];
if (self) {
self.delegate = delegate;
// Initialization code
}
return self;
}
-(IBAction)bump:(id)sender{
[self.delegate EBCellPressed:#"NAME"];
}
- (IBAction)open:(id)sender
{
}
#end
publicFeed . M
#import "PublicFeedViewController.h"
#import "FeedItemCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "InboxDetailViewController.h"
#import "SWRevealViewController.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface PublicFeedViewController (){
NSArray *NameLabel;
NSArray *StatusLabel;
NSMutableArray *feedArray;
}
#end
#implementation PublicFeedViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//The below code prompts the user for push notifications. If allowed, code in AppDelegate takes over and stores the token.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
// Do any additional setup after loading the view.
self.FeedTable.dataSource=self;
self.FeedTable.delegate=self;
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
[manager POST:#"www" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
self->feedArray = [responseObject objectForKey:#"feed"];
[self.FeedTable reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return feedArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier=#"Cell";
FeedItemCell *Cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!Cell){
Cell = [[FeedItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSLog(#"FEED ARRAY: %#", self->feedArray);
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
// Display recipe in the table cell
NSString *thumb_img = [tempDictionary objectForKey:#"thumb_img"];
NSString *thumb_path=#"http://buhzhyve.com/CI_REST_LOGIN/UPLOADS/thumbs/";
NSString *thumb_url = [thumb_path stringByAppendingString:thumb_img];
Cell.NameLabel.text=[tempDictionary objectForKey:#"first_name"];
Cell.StatusLabel.text=[tempDictionary objectForKey:#"message"];
Cell.msg_id=[tempDictionary objectForKey:#"msg_id"];
//Cell.status=[tempDictionary objectForKey:#"message"];
Cell.StatusLabel.lineBreakMode=0;
Cell.StatusLabel.numberOfLines=0;
NSString *commentCount = [tempDictionary objectForKey:#"comment_count"];
NSString *commentButtonText =[NSString stringWithFormat:#"Comments ( %# )",commentCount];
[Cell.commentButton setTitle:commentButtonText forState: UIControlStateNormal];
NSString *bumpCount = [tempDictionary objectForKey:#"bump_count"];
NSString *bumpButtonText =[NSString stringWithFormat:#"Bumps ( %# )",bumpCount];
[Cell.bumpButton setTitle:bumpButtonText forState: UIControlStateNormal];
//[Cell.StatusLabel sizeToFit];
NSString *created_string=[tempDictionary objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
Cell.timeLabel.text=ago;
//Cell.DefaultImg.image = [UIImage imageNamed:#"buhz_mini_logo.png"];
[Cell.DefaultImg setImageWithURL:[NSURL URLWithString:thumb_url]
placeholderImage:[UIImage imageNamed:#"buhz_mini_logo.png"]];
return Cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Ideally you should do lazy loading so that instead of creating a new textView each time, you just reuse the same one.
UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(82, 26, self.FeedTable.frame.size.width, 18)]; //This initial size doesn't matter
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
NSString *status = [tempDictionary objectForKey:#"message"];
temp.font =[UIFont fontWithName:#"System" size:12];
temp.text = status;
CGFloat textViewWidth = 218;
CGRect tempFrame = CGRectMake(82,26,textViewWidth,18); //The height of this frame doesn't matter.
CGSize tvsize = [temp sizeThatFits:CGSizeMake(tempFrame.size.width, tempFrame.size.height)]; //This calculates the necessary size so that all the text fits in the necessary width.
//Add the height of the other UI elements inside your cell
return tvsize.height + 70;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"commentSegue"]) {
}
}
#end
publicfeed .h
#import <UIKit/UIKit.h>
#interface PublicFeedViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *FeedTable;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
- (IBAction)addItem;
#end
So assuming that you're creating this button in code, this is how you could handle this.
This first line tells the button that when it's pressed, it needs to call this specific selector/method sent as the action.
[button addTarget:self action:#selector(showNextViewController) forControlEvents:UIControlEventTouchUpInside];
Then you would create this method in the same class.
- (void) showNextViewController
{
NewViewController *newViewController = [[NewViewController alloc] init]; //Edit this line of course to fit for your situation. I'm not sure if you're loading from an XIB or from a Storyboard, or neither.
newViewController.someVariable = someVariable;
newViewController.someOtherVariable = someOtherVariable;
[[[[[UIApplication sharedApplication] delegate] window] rootViewController].navigationController pushViewController:view animated:YES];
}
This will send the necessary data to the new view controller, and it will also display the new view on the screen with a back button.
Hope this works!
1. Ok so lets pretend this is your custom cell class.
in your .h file of the custom cell you need to add a protocol.
#import <UIKit/UIKit.h>
#interface CustomCell : UIView
#property (strong, nonatomic) id delegate; //this is used for sending messages out of the custom cell
//init
- (id)initWithFrame:(CGRect)frame andCatName:(NSString *)name andDelegate:(id)delegate;
#end
#protocol CustomCellProtocol <NSObject>
-(void)customCellSelected:(NSString *)cellName;
#end
what we actually did is something like creating a custom event that the class can throw out and everyone who subscribes to that can run a method when customCellSelected is thrown.
2. now when you create each custom cell with the init method you need to provide a delegate which kind of points to which class should the custom cell transfer the call to customCellSelected so in the init method you set that delegate.
- (id)initWithFrame:(CGRect)frame andDelegate:(id)delegate {
self = [super initWithFrame:frame];
if (self) {
self.delegate = delegate; //setting which class should be called when calling protocol methods.
// Your initialization code
}
return self;
}
3. now in your .m file of the custom cell, when the user presses your button and you enter your method , let it be buttonPressed
- (IBAction) buttonPressed:(id)sender {
[self.delegate customCellSelected:#"THE CELL'S NAME"]; // calling the protocol method.
}
now the call to the delegate method should be transferred to the vc because when you create the custom cell you use initWithFrame:(CGRect)frame andDelegate:(id)delegate and you transfer self as the delegate , so when [self.delegate customCellSelected:#"THE CELL'S NAME"]; is called it is actually called on the vc.
4. this is how you create the custom cell in the vc:
customCell *tempView = [[customCell alloc] initWithFrame:CGRectMake(X, Y, Width, Height) andDelegate:self]; // here you set the vc as the delegate
5.and now all you have to do is add the method customCellSelected to your vc code so it can called when the customCell is calling it.
- (void)customCellSelected:(NSString *)cellName {
self.selectedCell = cellName;
[self performSegueWithIdentifier:#"SelectedCell" sender:self];
}
6.then add this in the vc:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"SelectedCell"]) {
LevelSelectViewController *levelSelectViewController = (LevelSelectViewController *)segue.destinationViewController;
levelSelectViewController.cellName = self.selectedCell;
}
}
7.only thing you have to remember is to create a segue from your first vc to the second like this:
Currently I have custom UITablViewCell's (BIDSelectBusinessCustomCell) that are displayed in a tableView (myTableView). The custom cell is made up of a UIImageView and a label. When the view loads the labels are populated with the strings from my model. UIImageViews are blank. I want to be able for a user to 'tap' the UIImageView, select a picture from what is stored on their phone and for that image to be saved to the UIImageView.
From the below code I can get the 'tap' gesture, then the pickercontroller pops up and a user selects an image. The way the code is now one image that is selected is set for all of the UIImageViews. Which is understandable. But I want it to be set to that particular UIImageView and don't know how to.
Code:
#import <UIKit/UIKit.h>
#interface BIDBusinessSelectViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (strong, nonatomic) NSArray *linkedBusinessParseArray;
//Stores the array of models
#property (strong, nonatomic) NSMutableArray *linkedBusinessParseModelArray;
#property NSUInteger relevantIndex;
#property (strong, nonatomic) UIImage *tempImageHolder;
#end
#import "BIDBusinessSelectViewController.h"
#import <Parse/Parse.h>
#import "BIDBusinessModel.h"
#import "BIDSelectBusinessCustomCell.h"
#interface BIDBusinessSelectViewController () <ImageSelect>
{
BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
UIImage *choosenImage; //image to set the selected image
}
#end
#implementation BIDBusinessSelectViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
self.linkedBusinessParseModelArray = [[NSMutableArray alloc]init];
//create query
PFQuery *linkedBusinessParseQuery = [PFQuery queryWithClassName:#"linkedBusinessParseClass"];
//follow relationship
[linkedBusinessParseQuery whereKey:#"currentBusinessUserParse" equalTo:[PFUser currentUser]];
[linkedBusinessParseQuery whereKey:#"linkRequestSentParse" equalTo:#"Approved"];
[linkedBusinessParseQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.linkedBusinessParseArray = objects; //store them in my model array
//loop through model array from Parse
for (NSDictionary *dict in self.linkedBusinessParseArray) {
NSString *descPlaceNameParse = [dict objectForKey:#"placeDescriptionParse"];
NSLog(#"descPlacesNameParse: %#",descPlaceNameParse);
PFObject *tempObj = (PFObject *) dict;
NSString *tempObjString = tempObj.objectId;
NSLog(#"tempObjString (inside dict): %#", tempObjString);
//storing values from Parse into my model
BIDBusinessModel *userModel = [[BIDBusinessModel alloc]init];
userModel.descriptionModelParse = descPlaceNameParse;
userModel.objectIdModelParse = tempObjString;
[self.linkedBusinessParseModelArray addObject:userModel];
NSLog(#"self.linkedBusinessParseModelArray: %lu", (unsigned long)[self.linkedBusinessParseModelArray count]);
//Reload tableview. Has to go here in block otherwise it does not occur
[self.myTableView reloadData];
}
}];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Device has no camera"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[myAlertView show];
}
choosenImage = [UIImage imageNamed:#"pin.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell
}
#pragma mark -
#pragma mark Table Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.linkedBusinessParseModelArray.count; //returns count of model NSMutableArray
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Start cellforRowStIndex");
static NSString *CellIdentifier = #"Cell";
BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = choosenImage;
//cell.descLabel.text = [NSString stringWithFormat:#"bid= %d",indexPath.row];//set text from the model//Omitted for my desc
cell.descLabel.text = bizModel.descriptionModelParse;
cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method
//insted of settig the gesture hear set it on the custom cell
cell.ImageSelectDelegate = self; //setting the delegate
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
// hear implementation of delegate method
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
//open up the image picker
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
//UIImage holder to transfer to cellForRowAtIndexPath
choosenImage = aChosenImage;
NSIndexPath *indexPath = [self.myTableView indexPathForCell:aCell];
[self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
//get the model and set the choosen image
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
#import <UIKit/UIKit.h>
#protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
#end
#interface BIDSelectBusinessCustomCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *descLabel;
#property (strong, nonatomic) IBOutlet UIImageView *logoImage;
#property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte
#end
#import "BIDSelectBusinessCustomCell.h"
#implementation BIDSelectBusinessCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.logoImage = [[UIImageView alloc]init];
self.descLabel = [[UILabel alloc]init];
//set up gesture hear in the custom cell insted in the controller class
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapLogoImage:)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[tap setDelegate:self];
self.logoImage.userInteractionEnabled = YES;
[self.logoImage addGestureRecognizer:tap];
//[self addSubview:logoImage];
//[self addSubview:descLabel];
}
return self;}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
if([self.ImageSelectDelegate respondsToSelector:#selector(selectSetImageForSelectedLogImage:)])
{
[self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell
}
}
#end
Yup for this, i tried but finally i did something like this, go through this u may find some solution. and hope this helps u :)
//in custom cell "BIDSelectBusinessCustomCell.h"
#import <UIKit/UIKit.h>
//define a delegate method that is called each time when u tapped on cell
#protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
#end
#interface BIDSelectBusinessCustomCell : UITableViewCell <UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
UIImageView *logoImage; //your image holder
UILabel *descLabel; //label
}
#property (nonatomic, retain) UIImageView *logoImage;
#property (nonatomic, retain) UILabel *descLabel;
#property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte
#end
//in custom cell "BIDSelectBusinessCustomCell.m"
#import "BIDSelectBusinessCustomCell.h"
#implementation BIDSelectBusinessCustomCell
#synthesize logoImage;
#synthesize descLabel;
#synthesize ImageSelectDelegate;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
logoImage = [[UIImageView alloc]init];
descLabel = [[UILabel alloc]init];
//set up gesture hear in the custom cell insted in the controller class
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapLogoImage:)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[tap setDelegate:self];
logoImage.userInteractionEnabled = YES;
[logoImage addGestureRecognizer:tap];
[self addSubview:logoImage];
[self addSubview:descLabel];
}
return self;
}
- (void)dealloc
{
[logoImage release];
[descLabel release];
[super dealloc];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews
{
//in this method simply i am setting the frames of subviews
[super layoutSubviews];
self.logoImage.frame = CGRectMake(130, 2, 44,44 );
self.descLabel.frame = CGRectMake(20, 2, 60, 44);
}
- (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
if([self.ImageSelectDelegate respondsToSelector:#selector(selectSetImageForSelectedLogImage:)])
{
[self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell
}
}
#end
//in your view controller class u need to do something like this ;)
//ViewController.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (retain, nonatomic) IBOutlet UITableView *aTableView;
#property (nonatomic, retain) NSIndexPath *selectedIndexPath; //no need just try
#end
//in your "ViewController.m" file
#interface ViewController ()<UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControll erDelegate,ImageSelect>//delegate
{
BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
UIImage *choosenImage; //image to set the selected image
}
- (void)viewDidLoad
{
[super viewDidLoad];
choosenImage = [UIImage imageNamed:#"Star.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[aTableView release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4; //pass array check array contains valid objects
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if(cell == nil)
{
cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
cell.descLabel.text = [NSString stringWithFormat:#"bid= %d",indexPath.row];//set text from the model
cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method
//insted of settig the gesture hear set it on the custom cell
cell.ImageSelectDelegate = self; //setting the delegate
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
// hear implementation of delegate method
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
//open up the image picker
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
//UIImage holder to transfer to cellForRowAtIndexPath
choosenImage = aChosenImage;
NSIndexPath *indexPath = [aTableView indexPathForCell:aCell];
[self.aTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
//get the model and set the choosen image
BIDBusinessModel *bizModel;
bizModel = self.linkedBusinessParseModelArray[indexPath.row];
bizModel.image = aChosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Yes it is true this would set the image to every row..
Now what you can do is : -
While loading of tableViewCells just assign the tag of UIImageView as the (indexPath.Row).
This would assign unique tags to the ImageView.
You can easily get the tag of that imageView while tapping and now you can assign the image to particular imageView through tagValue of that imageView.
This would assign image to a particular imageView as all have unique tags.
Hope you got the answer of your problem.