Click image inside a TableView - ios

Good afternoon,
I'm trying to create a ProfileViewController (where the user profile is loaded, like profile image, likes and pictures) by making a click in the profile image inside a TableViewController (TableView).
At the moment is not working, because everything that I touch is going to a Segue (the post's segue where you can see the entry, likes and comments) but I need to create something (maybe it's a touch gesture) over the author image of that entry and show me his profile.
I have tried by creating a Tap Gesture Recognizer but it's not working. Also a Segue action directly in the Storyboard, and it's not working.
I'm going to show you an example, because at the ends it's like Facebook wall:
If I touch in the profile image it displays the user profile page with his information. I want to achieve that but with the image inside a TableView.
Here is what I got at the moment:
TableViewController.m
//
// CarTableViewController.m
// Copyright (c) 2014. All rights reserved.
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
//self.refreshControl.backgroundColor = [UIColor blackColor];
//self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (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 [_jsonArray count];
}
- (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 = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"imagen"] options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
-(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:
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"date"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"id"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"imagen"],
nil];
}
}
-(void)fetchJson {
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
NSLog(#"carModels ==> %#", _jsonArray);
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
}
#end
Regards,
Thanks in advance.

I used to do this with a gesture recognizer...
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapOnCheck:)];
tapped.numberOfTapsRequired = 1;
tapped.numberOfTouchesRequired = 1;
tapped.cancelsTouchesInView = YES;
[cell.imageView addGestureRecognizer:tapped];
As you can see, my target action was "tapOnCheck:" and my image was cell.imageView, but you can simply adapt this code to your code...
Hope this helped!
Bye

You can try simple solution.
Remove all segues from cell.
Then You need to override in CarTableViewCell, UIView's method which called:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
In this method detect touch location. Compare it with location of image.
If touch location is in image - send message to cell's delegate(it is your controller) which says that touch in Image on Cell.
Else - send message to cell's delegate which says that touch in other location in Cell.
Then choose segue to push.
Hope this will help you.

Related

Using TapGestureRecognizer with profileimage in TableViewController

Good afternoon,
I'm trying to implement a "see user profile" button which is going to show a new ViewController with the user information. I have implemented a TapGestureRecognizer over the image profile when the image is pressed (it's a TableViewController).
The main problem is when I press the user image it shows a wrong ProfileViewController because it seems that my TableViewController is not updating the #username when I press a different row (it's showing the latest profile I have seen).
I have tried following a lot of tutorials but it's not working in any case, because whenever I press the profile image it shows (and I have tested it) the wrong username.
What I have to do to update the username to the one I have pressed?
Find an image of my XCode: http://i.stack.imgur.com/FvNHg.jpg
Here is my TableViewController.m (it's in the #"segueprofile")
//
// CarTableViewController.m
// TableViewStory
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import "OtherProfileUserViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <Security/Security.h>
#import "SSKeychainQuery.h"
#import "SSKeychain.h"
#import "SBJson.h"
#interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
#end
#interface CarTableViewController ()
#end
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize like = _like;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
//self.refreshControl.backgroundColor = [UIColor blackColor];
//self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (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 [_jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)anIndexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.likeButton.tag = anIndexPath.row;
// Configure the cell...
cell.makeLabel.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"imagen"] options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:anIndexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
-(void)fetchJson {
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://webiste.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
//NSLog(#"LINK ==> %#", _jsonArray);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
//NSIndexPath *indexPath = [self tableView indexPathForCell:sender];
//NSLog(#"LINK ==> %#", indexPath);
if ([segue.identifier isEqualToString:#"segueprofile"]) {
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
if ([segue.identifier isEqualToString:#"segueprofile2"]) {
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects:
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"date"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"id"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"imagen"],
nil];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *) title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertView show];
}
- (IBAction)plusOne:(UIButton *)sender {
NSLog(#"%ld",(long)sender.tag);
}
#end
Any help will be much appreciated.
Regards,

Segue not updated inside TableViewController

Good afternoon,
I have created a Segue in my TableViewController where the user can touch the user profile and it sends that username to a ProfileViewController, where the user information is loaded (posts, image, info...) (something like a Facebook wall).
The problem is when I touch one user, it displays everything correctly, but when I touch another profile image, it displays the same ProfileViewController again, like the username is not updated and it's send wrong.
When I touch anywhere on the screen and then I touch again the user profile, in that case it works, but I need to make this work in every case.
I'm going to post my TableViewController if that helps you to find the problem because it's almost working, the only thing that I need to fix is that username that is not updated (Tap Gesture Recognizer over the image).
The segues are at the end of the code.
TableViewController.m
//
// CarTableViewController.m
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import "OtherProfileUserViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
//self.refreshControl.backgroundColor = [UIColor blackColor];
//self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (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 [_jsonArray count];
}
- (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 = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"imagen"] options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
-(void)fetchJson {
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
NSLog(#"carModels ==> %#", _jsonArray);
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
if ([segue.identifier isEqualToString:#"segueprofile2"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
}
#end
Thanks in advance.
OK, here is one of the options.
1. Delete all existing segues (segueprofile and segueprofile2)
2. Connect your tableviewcontroller (important: not tableview but controller itself) with your details controller by push-segue and name it segueprofile3
3. Refactor your code in the following manner
#property (nonatomic, strong) NSIndexPath * selectedIndexPath;
...
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)anIndexPath {
self.selectedIndexPath = anIndexPath;
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile3"]) {
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:selectedIndexPath.row] valueForKey:#"username"];
}
}
Another option. Place UIButton control right over avatar UIImageView. Create associated IBOutlet inside your CarTableViewCell class and make outlet connection.
#property (nonatomic, weak) UIButton * btnAvatar;
Next, modify CarTableViewController code
//1. declare new propery
#property (nonatomic, strong) id selectedProfile;
//2. implement future button tap handler
-(IBAction) btnAvatarDidPress:(id) sender {
int tag = ((UIButton *) sender).tag;
self.selectedProfile = [_jsonArray objectAtIndex:tag];
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
//Extend your cellForRowAtIndexPath method
- (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 = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.btnAvatar.tag = indexPath.row;
... rest of method
}
then remove didSelectRowAtIndexPath method, and connect btnAvatar Touch Up Inside action to btnAvatarDidPress method inside your controller code.
That's all I hope I've forgot nothing.
here is your example, in prepareForSegue, get the cell which button is in:
id v = sender;
while (![(v= v.superView) isKindOfClass:[UITableViewCell class]]
&& v!=nil) ;
if (v==nil)
// no ancestor view is cell.
else{
// now v is the cell.
NSIndexPath * indexPath = [self.tableView indexPathForCell:v];
// do the left
}

TableView Navigation using JSON (database data)

Good afternoon,
I used the following tutorial to create a TableView Navigation: http://www.techotopia.com/index.php/Implementing_TableView_Navigation_using_Xcode_Storyboards but with that example I can show static information.
Now I need to display images and texts from my database and I need some help to do that.
At the moment, that's my CarTableViewController.m
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
- (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];
}
- (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 [self.carModels count];
}
- (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;
}
-(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];
}
}
#end
I need to put the information from my database (author, date and picture) to carMakes, carModels and carImages to display it. I can get the values from my PHP file with JSON, but I need some help with the NSArray with JSON result because I never used it.
How can I do that?
That's my JSON result:
[{"id":"15","user":"1","image":"http:\/\/farmaventas.es\/images\/farmaventaslogo.png","date":"2014-09-13"}]
Thanks in advance.
NSMutableArray* dataSource = [[NSMutableArray alloc] init];
NSMutableDictionary* chevyVolt = [[NSMutableDictionary alloc] init];
chevyVolt[#"Make"] = #"Chevy";
chevyVolt[#"Model"] = #"Volt";
chevyVolt[#"Image"] = #"chevy_volt.jpg";
dataSource[0] = chevyVolt;
NSMutableDictionary* clubman = [[NSMutableDictionary alloc] init];
-- etc --
Inside cellForRow--
NSMutableDictionary* cellData = dataSource[[indexPath row]];
cell.makeLabel.text = cellData[#"Make"];
cell.modelLabel.text = cellData[#"Model"];
-- etc --
When you receive your JSON data, you have to decide what row it pertains to. If you somehow know that id 15 is for a Chevy Volt, you then presumably copy info out of the corresponding JSON element into the dictionary for the Chevy Volt. (Or, if you wait to receive the JSON to add the Chevy Volt row (seems more likely), you construct the dictionary for the Volt as above and add it to the end of the dataSource array, with the added info from the JSON.)

How to pass a UIImageView from UITableView (custom cell) to DetailViewController?

I'm tearing my hair out over this one. I'm trying to pass an image URL from my TableViewController to my DetailViewController (FullArticleViewController) so that I can set the UIImageView, and nothing I try seems to be working. See my code below:
MyTableViewController.h
#interface MyTableViewController : UIViewController <UISearchBarDelegate>{
IBOutlet UITableView *DoctorsTableView;
NSArray *Doctors;
NSMutableData *data;
NSArray *searchResults;
}
#property (strong, nonatomic) NSString *cellImageLink;
#property (strong, nonatomic) UINavigationBar *navigationBar;
MyTableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *DoctorsTableIdentifier = #"DoctorsCell";
DoctorsCell *cell = (DoctorsCell *)[tableView dequeueReusableCellWithIdentifier:DoctorsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DoctorsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSLog(#"Using the search results");
cell.firstnameLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"node_title"];
cell.descriptionLabel.text = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"Opening Paragraph"];
NSString *firstLink = [[NSString alloc] init];
firstLink = [[[searchResults objectAtIndex:indexPath.row] objectForKey:#"Image"] objectForKey:#"filename"];
NSString *secondLink = [[NSString alloc] init];
secondLink = [NSString stringWithFormat:#"URL HERE%#",firstLink];
NSLog(#"second link is %#", secondLink);
cellImageLink = secondLink;
[cell.featureImage sd_setImageWithURL:[NSURL URLWithString:secondLink]];
} else {
NSLog(#"Using the Full List!");
cell.firstnameLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"node_title"];
cell.descriptionLabel.text = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"Opening Paragraph"];
NSString *firstLink = [[NSString alloc] init];
firstLink = [[[Doctors objectAtIndex:indexPath.row] objectForKey:#"Image"] objectForKey:#"filename"];
NSString *secondLink = [[NSString alloc] init];
secondLink = [NSString stringWithFormat:#"URL HERE%#",firstLink];
NSLog(#"second link is %#", secondLink);
cellImageLink = secondLink;
[cell.featureImage sd_setImageWithURL:[NSURL URLWithString:secondLink]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FullArticleViewController *detailViewController = [[FullArticleViewController alloc]
initWithNibName:#"FullArticleViewController" bundle:nil];
if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"node_title"];
detailViewController.articleDetail = [searchResults objectAtIndex:indexPath.row];
} else {
detailViewController.title = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"node_title"];
detailViewController.articleDetail = [Doctors objectAtIndex:indexPath.row];
NSLog(#"%#", Doctors);
}
FullArticleViewController *viewController = [[FullArticleViewController alloc]
initWithNibName:#"DetailViewController"
bundle:nil];
viewController.featureImage = searchResults[indexPath.row][#"Image"][#"filename"];
[self.navigationController pushViewController:detailViewController animated:YES];
}
FullArticleViewController.h (detailview)
#interface FullArticleViewController : UIViewController
{
IBOutlet UIScrollView *scroller;
IBOutlet UILabel *firstnameLabel;
IBOutlet UILabel *descriptionLabel;
IBOutlet UILabel *bodyLabel;
}
#property (nonatomic, copy) NSDictionary *articleDetail;
#property (strong, nonatomic) IBOutlet UIImageView *featureImage;
-(IBAction)goBack:(id)sender;
FullArticleViewController.m (detailview)
#import "SDWebImage/UIImageView+WebCache.h"
#import "FullArticleViewController.h"
#import "DoctorsCell.h"
#import "MyTableViewController.h"
#interface FullArticleViewController ()
#end
#implementation FullArticleViewController
#synthesize articleDetail;
#synthesize featureImage;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
featureImage = [[UIImageView alloc] init];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 5000)];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
firstnameLabel.text = [articleDetail objectForKey:#"node_title"];
descriptionLabel.text = [articleDetail objectForKey:#"Opening Paragraph"];
bodyLabel.text = [articleDetail objectForKey:#"Body"];
}
MyTableViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FullArticleViewController *detailViewController = [[FullArticleViewController alloc]
initWithNibName:#"FullArticleViewController" bundle:nil];
if ([searchResults count]) {
detailViewController.title = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"node_title"];
detailViewController.articleDetail = [searchResults objectAtIndex:indexPath.row];
detailViewController.cellImageLink = searchResults[indexPath.row][#"Image"][#"filename"];
} else {
detailViewController.title = [[Doctors objectAtIndex:indexPath.row] objectForKey:#"node_title"];
detailViewController.articleDetail = [Doctors objectAtIndex:indexPath.row];
detailViewController.cellImageLink = Doctors[indexPath.row][#"Image"][#"filename"];
}
NSLog(#"cellImageLink = %#", detailViewController.cellImageLink);
[self.navigationController pushViewController:detailViewController animated:YES];
}
FullArticleViewController.m
Set the image in viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSLog(#"cellImageLink = %#", self.cellImageLink);
featureImage = [[UIImageView alloc] init];
//maybe set the frame here?
[self.featureImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://domainnamehere.com/%#",cellImageLink]]];
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 5000)];
firstnameLabel.text = [articleDetail objectForKey:#"node_title"];
descriptionLabel.text = [articleDetail objectForKey:#"Opening Paragraph"];
bodyLabel.text = [articleDetail objectForKey:#"Body"];
}
Typically you would set detail view properties upon cell selection right before pushing the new view controller. Something like this would do it:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
FullArticleViewController *detailView = [[FullArticleViewController alloc] init];
detailView.articleDetail = [searchResults objectAtIndex:indexPath.row];
[self.navigationController pushViewController detailView animated:YES];
}
Notice I am using the default initializer for your view controller and am also assuming you are using a UINavigationController. You may need to change one or both of these to fit your code.
Then, you would want to use the same SDWebImage category to set the image url in viewDidLoad of FullArticleViewController.m. It will probably look something like this:
- (void)viewDidLoad
{
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320, 5000)];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
firstnameLabel.text = [articleDetail objectForKey:#"node_title"];
descriptionLabel.text = [articleDetail objectForKey:#"Opening Paragraph"];
bodyLabel.text = [articleDetail objectForKey:#"Body"];
[self.featureImage sd_setImageWithURL::[NSURL URLWithString:[[self.articleDetail objectForKey:#"Image"] objectForKey:#"filename"]];
}

Can NOT segue between Storyboards

So I found a nice outline that gives me what I want. However, I can't switch to other storyboards?
How do I segue into other storyboards with a 'built in' window?
Included is my ViewController.M implementation file. This code seems to make a table on its own instead of use the storyboard (navigation controller)...
How do I make it work to segue to other storyboards?
#import "ViewController.h"
#interface ViewController ()
#end
#define getDataURL #"http://??.??.??.??/phpfile12.php"
#implementation ViewController
#synthesize json, storesArray, myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName : [UIColor whiteColor]};
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
//set the title
self.title = #"";
[self retrieveData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return storesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
//cell.textLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
//Retrieve the current city object for use with this indexPath.row
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
cell.textLabel.text = currentStore.storeName;
cell.detailTextLabel.text = currentStore.storeAddress;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - UITableView Delegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController * dvc = [[DetailViewController alloc]init];
//Retrieve the current selected city
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
dvc.name = currentStore.storeName;
dvc.address = currentStore.storeAddress;
dvc.startDate = currentStore.storeStartDate;
dvc.endDate = currentStore.storeEndDate;
dvc.startTime = currentStore.storeStartTime;
dvc.endTime = currentStore.storeEndTime;
dvc.totalSales = currentStore.storeTotalSales;
dvc.voids = currentStore.storeVoids;
dvc.discounts = currentStore.storeDiscounts;
dvc.guestCount = currentStore.storeGuestCount;
dvc.peopleServed = currentStore.storePeopleServed;
dvc.employeeClockIn = currentStore.storeEmployeeClockIn;
[self.navigationController pushViewController:dvc animated:YES];
}
#pragma mark - Methods
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Set up our cities array
storesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
//Create city object
NSString * sID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString * sAddress = [[json objectAtIndex:i] objectForKey:#"storeAddress"];
NSString * sName = [[json objectAtIndex:i] objectForKey:#"storeName"];
NSString * sStartDate = [[json objectAtIndex:i] objectForKey:#"storeStartDate"];
NSString * sStartTime = [[json objectAtIndex:i] objectForKey:#"storeStartTime"];
NSString * sEndDate = [[json objectAtIndex:i] objectForKey:#"storeEndDate"];
NSString * sEndTime = [[json objectAtIndex:i] objectForKey:#"storeEndTime"];
NSString * sTotalSales = [[json objectAtIndex:i] objectForKey:#"storeTotalSales"];
NSString * sVoids = [[json objectAtIndex:i] objectForKey:#"storeVoids"];
NSString * sDiscounts = [[json objectAtIndex:i] objectForKey:#"storeDiscounts"];
NSString * sGuestCount = [[json objectAtIndex:i] objectForKey:#"storeGuestCount"];
NSString * sPeopleServed = [[json objectAtIndex:i] objectForKey:#"storePeopleServed"];
NSString * sEmployeeClockIn = [[json objectAtIndex:i] objectForKey:#"storeClockIn"];
Store * myStore = [[Store alloc]initWithStoreID: (NSString *) sID andStoreName: (NSString *) sName andStoreStartDate: (NSString *) sStartDate andStoreStartTime: (NSString *) sStartTime andStoreEndDate: (NSString *) sEndDate andStoreEndTime: (NSString *) sEndTime andStoreTotalSales: (NSString *) sTotalSales andStoreVoids: (NSString *) sVoids andStoreDiscounts: (NSString *) sDiscounts andStoreGuestCount: (NSString *) sGuestCount andStorePeopleServed: (NSString *) sPeopleServed andStoreEmployeeClockIn: (NSString *) sEmployeeClockIn andStoreAddress: (NSString *) sAddress];
//Add our city object to our cities array
[storesArray addObject:myStore];
}
[self.myTableView reloadData];
}
#end
To instantiate a view controller from another storyboard you can use UIStoryboard storyboardWithName
UIViewController *dvc = [[UIStoryboard storyboardWithName:#"yourStoryboardName" bundle:nil] instantiateViewControllerWithIdentifier:#"yourViewIdentifier"];
[self.navigationController pushViewController:dvc animated:YES];
This is more a general answer, though.
I don't understand what you exactly asking but for simple segue i used this line of code
[self performSegueWithIdentifier:#"identifier" sender:self];
if you want to segue without linking than you have to give identifier to view controller and use this code below
UIViewController *homeViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"identifier"];
[self presentViewController:homeViewController animated:0 completion:nil];
I am not entire sure what you mean by "Segue to other storyboard"? The following code allows you to jump to a totally different view controller tree inside the same storyboard by a click of button or other action.
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *initViewController = [storyboard instantiateViewControllerWithIdentifier:#"SecondScreen"];
delegate.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
delegate.window.rootViewController = initViewController;
[delegate.window makeKeyAndVisible];
Main is the name of your storyboard that you want to jump into.
SecondScreen is the storyboard ID of the view controller. Most likely it is a navigation or a container. You will need to set "SecondScreen" under identity inspector.

Resources