I am developing an application in Xcode using objective-c. My problem is that I am trying to show admob advertising in my UITableViewController using a ToolBar but this bar is not showing anything. I have found a lot of responses on the internet about how to put this ToolBar in the UITableViewController, but for my case is not showing anything. I know that I have a low level of Xcode but I am trying to improve everyday.
This is my piece of code for the admob:
[self.navigationController setToolbarHidden:NO];
self.bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
self.bannerView.adUnitID = #"ca-app-pub-3940256099942544/2934735716"; //TEST!!!!!
self.bannerView.rootViewController = self;
[self.navigationController.toolbar addSubview:self.bannerView];
GADRequest *request = [GADRequest request];
request.testDevices = #[ #"",];
[self.bannerView loadRequest:request];
This is my MainTableViewController.h:
#import <UIKit/UIKit.h>
#import "Restaurant.h"
#import GoogleMobileAds;
#interface MainTableViewController : UITableViewController
#property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;
#property (nonatomic, strong) NSArray<Restaurant *> *originData;
#property (nonatomic, strong) NSMutableArray<Restaurant *> *filteredRest;
#property (nonatomic, assign) Boolean isFiltered;
#property (weak, nonatomic) IBOutlet UISearchBar *mySearchBar;
#property (strong, nonatomic) IBOutlet UITableView *RestTableView;
#property (weak, nonatomic) IBOutlet UIToolbar *admobToolBar;
#property(weak, nonatomic) IBOutlet GADBannerView *bannerView;
#end
And this is my MainTableviewController.m:
#import "MainTableViewController.h"
#import "SWRevealViewController.h"
#import "RestTableViewCell.h"
#import "RestViewController.h"
#import "Restaurant.h"
#interface MainTableViewController ()
#end
#implementation MainTableViewController
#synthesize mySearchBar, filteredRest, isFiltered, originData;
- (void)viewDidLoad {
[super viewDidLoad];
_barButton.target = self.revealViewController;
_barButton.action = #selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.RestTableView.tableFooterView = [[UIView alloc] init]; /*Esta linea hace que en la tabla solo aparezcan el numero de filas que tienes establecidas, es decir, que las vacias no aparezcan*/
[self.navigationController setToolbarHidden:NO];
self.bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
self.bannerView.adUnitID = #"ca-app-pub-3940256099942544/2934735716"; //TEST!!!!!
//self.bannerView.adUnitID = #"ca-app-pub-6926442062866079/7221537141";
self.bannerView.rootViewController = self;
[self.navigationController.toolbar addSubview:self.bannerView];
GADRequest *request = [GADRequest request];
request.testDevices = #[ #"",];
[self.bannerView loadRequest:request];
originData = #[
[[Restaurant alloc] init:#"80 Grados" descripiton:#"Malasaña" image:#"80_grados.jpg"],
[[Restaurant alloc] init:#"90 Grados" descripiton:#"Retiro" image:#"90_grados.jpg"],
[[Restaurant alloc] init:#"B&B Babel" descripiton:#"Barrio de Chueca" image:#"babel.jpg"],
[[Restaurant alloc] init:#"Babelia" descripiton:#"Barrio de Salamanca" image:#"babelia.jpg"],
[[Restaurant alloc] init:#"Bacira" descripiton:#"Chamberí" image:#"bacira.jpg"],
[[Restaurant alloc] init:#"Bar Galleta" descripiton:#"Malasaña" image:#"bar_galleta.jpg"],
[[Restaurant alloc] init:#"Bar Tomate" descripiton:#"Chamberí" image:#"bar_tomate.jpg"],
filteredRest = [NSMutableArray new];
isFiltered = NO;
}
- (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.
if (isFiltered == YES) {
return filteredRest.count;
} else {
return originData.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
RestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [filteredRest objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[filteredRest objectAtIndex:indexPath.row].image];
} else {
cell.TitleLabel.text = [originData objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [originData objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[originData objectAtIndex:indexPath.row].image];
}
cell.RestImage.layer.cornerRadius = 6;
cell.RestImage.clipsToBounds = YES;
cell.RestImage.layer.borderWidth = 1;
return cell;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowDetails"]){
RestViewController *restviewcontroller = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
if (isFiltered) {
restviewcontroller.DetailModal = filteredRest[myIndexPath.row];
} else {
restviewcontroller.DetailModal = originData[myIndexPath.row];
}
}
}
#end
The ToolBar is not showing anything:
What can be wrong?
I need your help! Than you very much for your responses!
Is there any reason you are using a UIToolBar to show this ad?
I would recommend instead of using a UITableViewController, use a UIViewController and make a property in there for a UITableView.
Once you have done that you can setup your constraints like so:
=====
top
tableview
ad view (set height)
bottom
======
The benefit of using a UIViewController with a table view in it is that you can put whatever else on the screen, not just the tableview :)
I hope that helps! Feel free to reply if you need more info on where to start with that!
Related
I added UISearchBar in UITableView and than added it inside UIView. I'm adding UIView on window and everything works fine. searchBarShouldBeginEditing is triggering and displaying logs however, searchBarTextDidBeginEditing is not triggering. Below is my code:
AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
self.frame = appDelegate.window.frame;
[appDelegate.window addSubview:self];
inside myView.h:
#property(strong, nonatomic) UISearchController *searchController;
and inside myView.m:
- (void)drawRect:(CGRect)rect {
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.userInteractionEnabled = YES;
tblDropdown.tableHeaderView = self.searchController.searchBar;
arrSeached = [NSMutableArray array];
}
Maybe, the problem is that your view controller or view (I do know without all code) has not added the protocol correctly.
Anyway, this is a example using UISearchController:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating>
#property (nonatomic, weak) IBOutlet UITableView * tableView;
#property (nonatomic, strong) UISearchController * searchController;
#property (nonatomic, strong) NSMutableArray * allItems;
#property (nonatomic, strong) NSMutableArray * filteredItems;
#property (nonatomic, weak) NSArray * displayedItems;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize tableView;
#synthesize searchController;
#synthesize allItems;
#synthesize displayedItems;
#synthesize filteredItems;
- (void)viewDidLoad {
[super viewDidLoad];
// Create a list
self.allItems = [[NSMutableArray alloc] init];
[self.allItems addObject:#"One"];
[self.allItems addObject:#"Two"];
[self.allItems addObject:#"Three"];
// Create a list to hold search results (filtered list)
self.filteredItems = [[NSMutableArray alloc] init];
// Initially display the full list. This variable will toggle between the full and the filtered lists.
self.displayedItems = self.allItems;
// Here's where we create our UISearchController
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.delegate = self;
[self.searchController.searchBar sizeToFit];
// Add the UISearchBar to the top header of the table view
self.tableView.tableHeaderView = self.searchController.searchBar;
// Hides search bar initially. When the user pulls down on the list, the search bar is revealed.
[self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
return [self.displayedItems count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)anIndexPath {
UITableViewCell * cell = [aTableView dequeueReusableCellWithIdentifier:#"FruitCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] init];
}
cell.textLabel.text = [self.displayedItems objectAtIndex:anIndexPath.row];
return cell;
}
// When the user types in the search bar, this method gets called.
- (void)updateSearchResultsForSearchController:(UISearchController *)aSearchController {
NSLog(#"updateSearchResultsForSearchController");
NSString *searchString = aSearchController.searchBar.text;
NSLog(#"searchString=%#", searchString);
// Check if the user cancelled or deleted the search term so we can display the full list instead.
if (![searchString isEqualToString:#""]) {
[self.filteredItems removeAllObjects];
for (NSString *str in self.allItems) {
if ([searchString isEqualToString:#""] || [str localizedCaseInsensitiveContainsString:searchString] == YES) {
NSLog(#"str=%#", str);
[self.filteredItems addObject:str];
}
}
self.displayedItems = self.filteredItems;
}
else {
self.displayedItems = self.allItems;
}
[self.tableView reloadData];
}
#end
I have two controllers: the main one is LocationItemTableViewController and contains all the graphic elements and the unfiltered table; the other one is SearchResultsTableViewController, which is used to process the results of the search. I want the search results to be displayed on LocationItemTableViewController, in a new table.
When the search starts updateSearchResultsForSearchController is called on the main controller and this assigns the results of the search to resultsController (an instance of SearchResultsTableViewController) which displays them on the main view controller.
Issues:
When updateSearchResultsForSearchController is called my NavigationBar unexpectedly disappears! Why?
When updateSearchResultsForSearchController is called the results are displayed correctly but if I scroll them up they pass underneath the SearchBar and then they show up again where there should be the NavigationBar..
When I click on a button that I have implemented in cellForRowAtIndexPath it gives me this warning:
Warning: Attempt to present UIAlertController: xxxxxxx on LocationItemTableViewController: xxxxxx whose view is not in the window hierarchy!
The button is supposed to call a kind of action sheet (UIAlertController) on LocationItemTableViewController.
Clearly there is something conceptually wrong in what I am doing but I cannot understand what...
Any hint please? Thanks!
LocationItemTableViewController.h
#interface LocationItemTableViewController : UIViewController <UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating, UIAlertViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, NSCoding, UIActionSheetDelegate>
#property (strong,nonatomic) NSMutableArray *filteredLocationItemArray; //Filtered results array
#property (nonatomic, retain) IBOutlet UINavigationBar *NavigationBar;
LocationItemTableViewController.m
#interface LocationItemTableViewController ()
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (nonatomic, strong) SearchResultsTableViewController *resultsController;
- (void)viewDidLoad
{
[super viewDidLoad];
self.searchResults = [NSMutableArray arrayWithCapacity:[self.LocationItemArray count]];
resultsController = [[SearchResultsTableViewController alloc] init];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:resultsController];
self.searchController.searchResultsUpdater = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
self.searchController.searchBar.placeholder = nil;
[self.searchController.searchBar sizeToFit];
self.searchController.dimsBackgroundDuringPresentation = YES;
self.searchController.searchBar.delegate = self;
self.searchController.delegate = self;
self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y + NavigationBar.bounds.size.height +20, self.tableView.frame.size.width, self.tableView.contentSize.height);
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = [self.searchController.searchBar text];
NSString *scope = nil;
[self updateFilteredContentForProductName:searchString type:scope];
if (self.searchController.searchResultsController) {
resultsController.filteredEvents = self.searchResults;
resultsController.tableView.frame = CGRectMake(0,0,[[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height-ToolBar.bounds.size.height);
//Now reload the table but this time containing the search results
[resultsController.tableView reloadData];
}
}
SearchResultsTableViewController.h
#interface SearchResultsTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *filteredEvents;
SearchResultsTableViewController.m
#interface SearchResultsTableViewController ()
#property (nonatomic, strong) LocationItemTableViewController *instanceOfLocationItemTableViewController;
#end
#implementation SearchResultsTableViewController
#synthesize instanceOfLocationItemTableViewController;
- (void)viewDidLoad
{
[super viewDidLoad];
//Create instance of LocationItemTableViewController.h
instanceOfLocationItemTableViewController = [[LocationItemTableViewController alloc] init];
[self.tableView setAllowsSelection:NO];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.filteredEvents ? 1 : 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"CALLED numberOfRowsInSection --: %lu", (unsigned long)[self.filteredEvents count]);
return [self.filteredEvents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create a new LocationItem Object
LocationItem *locationItem = nil;
locationItem = [self.filteredEvents objectAtIndex:[indexPath row]];
static NSString *CellIdentifier = #"SearchResultCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
....
[[cell textLabel] setText:[locationItem name]];
return cell;
}
I am trying to send data back from one view controller to another. I am doing this based off another Q & A in stack overflow but I still have not go the hang of it.
LocationViewController.h
#import "ViewController.h"
#class LocationViewController;
#protocol LocationViewControllerDelegate <NSObject>
- (void)addItemViewController:(LocationViewController *)controller didFinishEnteringItem:(NSString *)item;
#end
#interface LocationViewController : UIViewController
#property (nonatomic, strong) UILabel *locationLabel;
#property (nonatomic, strong) UITextField *locationField;
#property (nonatomic, strong) NSString *fieldText;
#property (nonatomic, weak) id <LocationViewControllerDelegate> delegate;
- (instancetype) init;
-(void)saveButtonPressed;
#end
LocationViewController.m
#import "LocationViewController.h"
#import "SetScoringTableViewController.h"
#import "GameDetailsTableViewController.h"
#interface LocationViewController ()
#end
#implementation LocationViewController
#synthesize locationField;
#synthesize locationLabel;
#synthesize fieldText;
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
//label
locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 1000, 20)];
[locationLabel setText: #"Location:"];
[self.view addSubview:locationLabel];
//text field
locationField = [[UITextField alloc] initWithFrame:CGRectMake(20, 150, 300, 35)];
[locationField setBorderStyle: UITextBorderStyleRoundedRect];
locationField.text = #"Enter Location Here";
[self.view addSubview:locationField];
//save button
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle: #"Save" style: UIBarButtonItemStylePlain target: self action: selector(saveButtonPressed)];
self.navigationItem.rightBarButtonItem = saveButton;
}
-(void)saveButtonPressed {
locationField.text = locationField.text;
[self.delegate addItemViewController:self didFinishEnteringItem:locationField.text];
NSLog(#"%#", locationField.text);
[self.navigationController popViewControllerAnimated:YES ];
[self performSelector:#selector(saveButtonPressed) withObject:nil afterDelay:0.25];
GameDetailsTabelViewController *gameDetails = [[GameDetailsTableViewController alloc] init];
[gameDetails.tableView reloadData]
}
GameDetailsTableViewController.m:
-(void)addItemViewController:(LocationViewController *)controller didFinishEnteringItem:(NSString *)item {
LocationViewController *locationView = [[LocationViewController alloc]initWithNibName:#"LocationViewController" bundle:nil];
locationView.delegate = self;
[[self navigationController]pushViewController:locationView animated:YES];
item = fieldText;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifer1 = #"GameDetailsLocationCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer1];
label = (UILabel *)[cell viewWithTag:0];
label.text = [NSString stringWithFormat: #"%#", fieldText];
return cell;
}
}
When I run this I get null for the item. I would like to know why I am getting null on the item which is preventing my from further usage of this program.
I am guessing that you wanna send some info from LocationVC to GameDetailVC.
In that case
LocationViewController.m
-(void)saveButtonPressed {
if([self.delegate respondsToSelector:#selector(addItemViewController:didFinishEnteringItem:)]{
[self.delegate addItemViewController:self didFinishEnteringItem:locationField.text];
}
[self.navigationController popViewControllerAnimated:YES ];
}
GameDetailsTableViewController.m:
-(void)addItemViewController:(LocationViewController *)controller didFinishEnteringItem:(NSString *)item {
//do something with item?
//reload table data?
[self.tableview reloadData];
}
Hope it helps.
check for errors.
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
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: