Custom Delegate, dismiss popover from another view - iphone

I could use some help with custom delegates. I'm trying to make a protocol that sends a message to its delegate to dismiss the popover view. Here is what I'm trying.
In the popoverViewController.h
#import <UIKit/UIKit.h>
#protocol MyPopoverDelegate <NSObject>
-(void) didSelectLanguage;
#end
#interface Popover : UITableViewController{
id <MyPopoverDelegate> delegate;
NSMutableArray *languageData;
}
#property (nonatomic, assign) id <MyPopoverDelegate> delegate;
#end
.m
#synthesize delegate;
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"You selected %#", [languageData objectAtIndex:[indexPath row]]);
[self.delegate didSelectLanguage];
}
...
And in the ViewController that presents the popover
#import <UIKit/UIKit.h>
#import "popoverViewController.h"
#interface ChoicesChoices : UIViewController <UIPopoverControllerDelegate, MyPopoverDelegate>{
UIPopoverController *popover;
}
- (IBAction)facebook:(id)sender;
- (IBAction)twitter:(id)sender;
- (IBAction)sms:(id)sender;
- (IBAction)copy:(id)sender;
- (IBAction)email:(id)sender;
- (IBAction)home:(id)sender;
- (IBAction)mute:(id)sender;
- (IBAction)note:(id)sender;
#property (nonatomic, retain) UIPopoverController* popover;
#end
and .m
#synthesize popover;
...
- (void)didSelectLanguage{
[popover dismissPopoverAnimated:YES];
NSLog(#"didSelectLanguage fired");
}
When I select a row in the table of the popover, didSelectLanguage does not get called. Any ideas on what I might be doing wrong? Thanks for your help.

Make sure you are setting your delegate to the be the view controller that is presenting your popover. Something like this in ChoicesChoices.m:
- (void)presentPopover
{
// assuming ARC for all allocations
Popover *myController = [Popover new];
myController.delegate = self;
self.popover = [[UIPopoverController alloc] initWithContentViewController:myController];
[self.popover presentPopover...]; // two flavors here, FromRect: and FromBarButtonItem:, that's left up to you to choose which one is correct.
}

Make sure you set the delegate in the presenting view controller when you create the instance of your custom class.
popover.delegate = self
Also, it looks like your property is a standard popover controller instead of an instance of your custom view controller.

Related

calling functions and passing information between views

Thanks in advance for your help!
In the main ViewController.m of my project I am adding a customized tableView like so:
messageController = [[MyMessagesController alloc] initWithStyle:UITableViewStylePlain];
[self addChildViewController:messageController];
[self.view addSubview:messageController.view];
Then, in the MyMessagesController.m section tableView didSelectRowAtIndexPath: I'd like to write code that would take effect in the ViewController.m where it was created and added as a childViewController.
How can I access the functions of the ViewController.m from MyMessagesController.m?
Can I make it a delegate somehow so I could call [delegate functionName];?
Could I pass information back to the ViewController.m? About which of the rows in table was selected by sending through an NSString or NSArray or anything?
Yes, use a delegate, if you are unsure how best to accomplish this, here is a good reference from Apple about delegate programming
Got it figured out, here's how you turn one viewController into a delegate for another:
In the .h of the parent controller -
#interface ViewController : UIViewController <NameOfDelegate> {
In the .m of the parent controller, once you create the new view -
newViewController.delegate = self;
and also:
- (void)functionToCall:(id)sender {
NSLog(#"Function Called!!!");
}
In the .h of the newViewController you're adding -
#protocol NameOfDelegate;
#interface newViewController : UIViewController/OR/TableViewController {
id <NameOfDelegate> delegate;
}
#property (nonatomic, strong) id <NameOfDelegate> delegate;
#end
#protocol NameOfDelegate
- (void)functionToCall:(id)sender;
#end
in the .m of the newViewController -
#implementation newViewController
#synthesize delegate;
and when you're ready to call the function in your delegate -
[delegate functionToCall:self];

Can't close popover after selecting item within table view

I am creating and iPad application using XCode version 4.3.2. I am having trouble figuring out how to close a popover that is created in a storyboard.
On my main screen I have a button. On the storyboard, I have a segue defined from that button to my popover. My popover is a table view controller. After selecting an item in the popover table view, I am sending the selected information back to the parent and attempting to close the popover. Everything works except I cannot get the popover to close.
The code for the main screen .m file:
#import "SectionViewController.h"
#import "SortByTableViewController.h"
#interface SectionViewController () <SortByTableViewControllerDelegate>
#end
#implementation SectionViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"DisplaySortByOptions"])
{
SortByTableViewController *popup = (SortByTableViewController*)segue.destinationViewController;
popup.selectedSection = self.selectedSection;
popup.receivedOption = self.selectedItemCharacteristic;
popup.delegate = self;
}
}
- (void)sortByTableViewController:(SortByTableViewController *)sender
returnedOption:(ItemCharacteristic *)returnedOption
{
if(!returnedOption)
{
[self.sortByButton setTitle:#"SHOW ALL" forState:UIControlStateNormal];
}
else
{
[self.sortByButton setTitle:returnedOption.name forState:UIControlStateNormal];
}
self.itemCharacteristic = returnedOption;
[self dismissViewControllerAnimated:YES completion:nil]; //THIS DOES NOT CLOSE THE POPOVER
}
The code for the popover .h file:
#import <UIKit/UIKit.h>
#class SortByTableViewController;
#protocol SortByTableViewControllerDelegate <NSObject>
- (void)sortByTableViewController:(sortByTableViewController *)sender
returnedOption:(ItemCharacteristic *)returnedOption;
#end
#interface SortByTableViewController : UITableViewController
#property (nonatomic, strong) Section *selectedSection;
#property (nonatomic, strong) ItemCharacteristic *receivedOption;
#property (nonatomic, weak) id <SortByTableViewControllerDelegate> delegate;
#end
The code for the popover .m file:
#import "SortByTableViewController.h"
#interface SortByTableViewController () <UITableViewDelegate>
#end
#implementation SortByTableViewController
#synthesize selectedSection = _selectedSection;
#synthesize receivedOption = _receivedOption;
#synthesize delegate = _delegate;
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ItemCharacteristic *itemCharacteristic = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.delegate sortByTableViewController:self returnedOption:itemCharacteristic];
[self dismissViewControllerAnimated:YES completion:nil]; //THIS DOESN'T WORK
[self.navigationController popViewControllerAnimated:YES]; //THIS DOESN'T WORK EITHER
}
#end
Thanks for any help or guidance.
I found the answer. I had to add the following property to my main screen:
#property (nonatomic, strong) UIPopoverController *sortByPopoverController;
Then, when launching the popover, I included this:
UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue *)segue;
self.sortByPopoverController = popoverSegue.popoverController;
Including that code allowed me to properly dismiss the popover when the delegate called back:
[self.sortByPopoverController dismissPopoverAnimated:YES];
in swift just call this
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.dismissViewControllerAnimated(true, completion: nil)
}

Using delegate to pass data between views

I am building a utility application which shares data between main view and flip view. Actually, it is not exactly the flip view that's holding data, it's the custom view that's an instance of the flip view when it gets loaded. I have explained the specifics in my previous thread here, but I haven't got a solution yet. And I have redeveloped my code, hopefully this time I could make myself clear.
The general concept here is I create and store data in my main view, and pass it to the flip side view using the predefined delegate in the FlipViewController. Then in the FlipViewController, I store the data in my own delegate and pass it to the custom view which implements my own delegate method. The following is the main portions of the code.
MainViewController.m (only adopts <FlipsideViewControllerDelegate> protocol)
- (IBAction)showInfo:(id)sender {
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideView" bundle:nil];
controller.delegate = self;
controller.chart = data;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
FlipsideViewController.h
#protocol FlipsideViewControllerDelegate;
#protocol ChartDelegate;
#interface FlipsideViewController : UIViewController {
id <FlipsideViewControllerDelegate> delegate;
id <ChartDelegate> delegate2;
DataModel *chart;
}
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
#property (nonatomic, assign) id <ChartDelegate> delegate2;
#property (nonatomic, retain) DataModel *chart;
- (IBAction)done:(id)sender;
#end
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#protocol ChartDelegate <NSObject>
- (void)getParams:(DataModel *)dataModel;
#end
FlipsideViewController.m
#synthesize delegate, delegate2;
#synthesize chart;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
if ([delegate2 respondsToSelector:#selector(getParams:)]) {
[delegate2 getParams:chart];
}
}
customDrawing.h
#interface customDrawing : UIView <ChartDelegate>{
DataModel *chartData;
}
#property (nonatomic, retain) DataModel *chartData;
#end
customDrawing.m
#synthesize chartData;
-(void)getParams:(DataModel *)dataModel{
chartData = dataModel;
}
It turns out the data didn't get passed to the chartData object in my custom view. HELP?
You are missing the fundamentals. I do not think you need delegates to achieve this task but here we go.
A protocol is like a contract. In you FlipsideViewController class you defined the protocol which essentially states if you conform to this protocol then you must implement this method.
How do you conform to a protocol?
In MainViewController the #interface will look something like this
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
The fact that you have the protocol written in angled brackets means that you promise to conform to the protocol and therefore have to implement
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
in your MainViewController.m.
Now when MainNavigationController set's itself as the delegate (controller.delegate = self;) it finishes the link. This allows the FlipsideViewController to call
[delegate flipsideViewControllerDidFinish:self];
Which will call the method defined in MainViewController which dismisses the modal view controller.
You have defined a second protocol (you could have added the method to the first and then you would not have to adopt two protocols) and as others have pointed out you have not linked the classes up by doing
controller.delegate2 = self;
This would not solve your problem. You would still need to conform to the ChartDelegate by adding it to the declaration. Once you have done that you will still not be out of the water because the method is not correct.
Full solution - not using delegates as they are not really required here
MainViewController.h
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
- (IBAction)showInfo:(id)sender;
#end
MainViewController.m
#implementation MainViewController
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)showInfo:(id)sender
{
FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:#"FlipsideView" bundle:nil];
controller.delegate = self;
/*
* The labelText property is defined in the header for FlipsideViewController
* In this case this is the easiest way to get data from this controller to
* the controller we are about to display
*/
controller.labelText = #"WHAT EVER YOU WANT TO SEND"; // <---- sending data
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
FlipsideViewController.h
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController
/*
* These properties have been added. The label is used for displaying the text
* and needs to be hooked up in Interface builder
*
* The NSString is the property that is holding the data passed from MainViewController
*/
#property (nonatomic, retain) IBOutlet UILabel *testLabel;
#property (nonatomic, copy) NSString *labelText; from MainViewControlller
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
#end
FlipsideViewController.m
#implementation FlipsideViewController
#synthesize delegate = _delegate;
/*
* We need to synthesise out properties so we get our getters and setters created
*/
#synthesize testLabel = _testLabel;
#synthesize labelText = _labelText;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
/*
* This is called once the view is set up and all connections have been made in
* interface builder. Therefore we can now set the text of our test label
*/
self.testLabel.text = labelText;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Actions
- (IBAction)done:(id)sender
{
[self.delegate flipsideViewControllerDidFinish:self];
}
- (void)dealloc
{
/*
* Memory management for the ivars we added
*/
[_testLabel release];
[_labelText release];
[super dealloc];
}
#end
You have two properties: delegate and delegate2. You are assigning a value to delegate, but calling the method on delegate2 later.
You need to assign the delegate2 (your customDrawing class). You are only assigning the delegate.

Xcode: Does the delegating object HAVE to send a message to the delegate object?

I'm trying to assign SecondViewController as a delegate object of FirstViewController (if I understand correctly). However FirstViewController doesn't send any messages to SecondViewController.
Am I allowed to pretend as though SecondViewController did get a message from FirstViewController and respond to the FirstViewController? (Note: My SecondViewController is in charge of a view that has a button. When I press the button on my SecondViewController's view I want it to tell the FirstViewController to update its view)
FirstViewController.h
#import <UIKit/UIKit.h>
#protocol FirstViewControllerDelegate <NSObject>
#optional
- (void) setAnotherLabel;
#end
#interface FirstViewController : UIViewController {
IBOutlet UILabel *label;
id <FirstViewControllerDelegate> delegate;
}
#property (nonatomic, retain) IBOutlet UILabel *label;
#property (nonatomic, assign) id <FirstViewControllerDelegate> delegate;
- (void) pretendLabel;
- (void) realLabel;
#end
FirstViewController.m
#import "FirstViewController.h"
#implementation FirstViewController
#synthesize label;
#synthesize delegate;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void) setAnotherLabel;
{
label.text =#"Real";
[self.view setNeedsDisplay];
}
- (void) pretendLabel;
{
label.text =#"Pretend";
[self.view setNeedsDisplay];
}
- (void) realLabel;
{
[self setAnotherLabel];
}
- (void)viewDidLoad
{
[super viewDidLoad];
label.text=#"Load";
[self pretendLabel];
}
...
#end
SecondViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "FirstViewController.h"
#interface SecondViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, FirstViewControllerDelegate>
{
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction) sendPressed:(UIButton *)sender;
- (IBAction) cancelPressed:(UIButton *)sender;
#end
SecondViewController.m
#import "SecondViewController.h"
#implementation SecondViewController
- (IBAction) sendPressed:(UIButton *)sender
{
FirstViewController *fvc = [[FirstViewController alloc] init];
[fvc setDelegate:self];
//how do I find out if I'm actually the delegate for FirstViewController at this point?
[fvc realLabel];
self.tabBarController.selectedIndex = 0;//switch over to the first view to see if it worked
}
There are a few issues with this and what appears to be a bit of confusion.
I assume that FirstViewController and SecondViewController are in separate tabs in the tab bar controller.
In the sendPressed: method, you're creating a new instance of FirstViewController - this is not the same FirstViewController that is in your tab bar controller and why calling realLabel has no effect.
The second point is that you appear to misunderstand how delegation works - there is no reason for a delegate in the code you posted.
Good read for getting to grips with delegates: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html
As for a solution to your problem there are a few options:
Post a notification from SecondViewController that FirstViewController is observing (lots of information available on the net regarding notifications).
Get the specific instance of FirstViewController within the self.tabBarController.viewControllers array and call the method from there. Something like...
- (IBAction) sendPressed:(UIButton *)sender
{
for(UIViewController *controller in self.tabBarController.viewControllers)
{
if([controller isKindOfClass:[FirstViewController class]])
{
FirstViewController *firstViewController = (FirstViewController *)controller;
[firstViewController realLabel];
}
}
self.tabBarController.selectedIndex = 0;//switch over to the first view to see if it worked
}
There are more options available than this, but the above will give you a good start into researching the best approach for your need.
Hope this helps.

Problem with Delegate and NavigationController

I'm using a NavigationController to "push" viewControllers from the rootView of an app.
I want to use delegates to comunicate the currently loaded view and the rootViewController. I was able to do this using NSNotificationCenter, but want give a try to delegates for this particular situation, since the communication is always going to be one-to-one.
In the view that is pushed, I declared the following delegate protocole in the header file:
#import <UIKit/UIKit.h>
#protocol AnotherViewControllerDelegate;
#interface AnotherViewController : UIViewController {
id <AnotherViewControllerDelegate> delegate;
}
- (IBAction) doAction;
#property (nonatomic, assign) id delegate;
#end
#protocol AnotherViewControllerDelegate <NSObject>
- (void) doDelegatedAction:(AnotherViewController *)controller;
#end
The doAction IBAction is connected to a UIButton in the view. In my implementation file, I added:
#import "AnotherViewController.h"
#implementation AnotherViewController
#synthesize delegate;
- (IBAction) doAction {
NSLog(#"doAction");
[self.delegate doDelegatedAction:self];
}
In my RootViewController.h I added AnotherViewControllerDelegate to the interface declaration:
#interface RootViewController : UIViewController <AnotherViewControllerDelegate> {...
and this to my implementation file
- (void) doDelegatedAction:(AnotherViewController *)controller {
NSLog(#"rootviewcontroller->doDelegatedAction");
}
Unfortunately it's not working. doDelegatedAction in the rootViewController is not been called. I suspect it's because of the way I push the AnotherViewController:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherViewController" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
Should I tell, in any way, to AnotherViewController that its delegate is going to be RootViewController just in the moment it's been pushed? or am I missing something else?
You need to set the delegate of AnotherViewController to the rootViewController in order for everything to be connected up properly.
If you are initializing AnotherViewController in your rootViewController it would be:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherViewController" bundle:nil];
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];