ios 如何设置一个简单的委托来在两个视图控制器之间进行通信?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6168919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:08:30  来源:igfitidea点击:

How do I set up a simple delegate to communicate between two view controllers?

iosobjective-ciphonedelegates

提问by jini

I have two UITableViewControllersand need to pass the value from the child view controller to the parent using a delegate. I know what delegates are and just wanted to see a simple to follow example.

我有两个UITableViewControllers,需要使用委托将值从子视图控制器传递给父视图。我知道代表是什么,只是想看看一个简单的例子。

Thank You

谢谢你

回答by Simon Whitaker

Simple example...

简单的例子...

Let's say the child view controller has a UISliderand we want to pass the value of the slider back to the parent via a delegate.

假设子视图控制器有一个UISlider,我们想通过委托将滑块的值传递回父视图。

In the child view controller's header file, declare the delegate type and its methods:

在子视图控制器的头文件中,声明委托类型及其方法:

ChildViewController.h

子视图控制器.h

#import <UIKit/UIKit.h>

// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;

// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController

// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;

// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue: 
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;

@end

// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>

- (void)childViewController:(ChildViewController*)viewController 
             didChooseValue:(CGFloat)value;

@end

In the child view controller's implementation, call the delegate methods as required.

在子视图控制器的实现中,根据需要调用委托方法。

ChildViewController.m

子视图控制器.m

#import "ChildViewController.h"

@implementation ChildViewController

- (void)handleCloseButton:(id)sender {
    // Xcode will complain if we access a weak property more than 
    // once here, since it could in theory be nilled between accesses
    // leading to unpredictable results. So we'll start by taking
    // a local, strong reference to the delegate.
    id<ChildViewControllerDelegate> strongDelegate = self.delegate;

    // Our delegate method is optional, so we should 
    // check that the delegate implements it
    if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
        [strongDelegate childViewController:self didChooseValue:self.slider.value];
    }
}

@end

In the parent view controller's header file, declare that it implements the ChildViewControllerDelegateprotocol.

在父视图控制器的头文件中,声明它实现了ChildViewControllerDelegate协议。

RootViewController.h

根视图控制器.h

#import <UIKit/UIKit.h>
#import "ChildViewController.h"

@interface RootViewController : UITableViewController <ChildViewControllerDelegate>

@end

In the parent view controller's implementation, implement the delegate methods appropriately.

在父视图控制器的实现中,适当地实现委托方法。

RootViewController.m

根视图控制器.m

#import "RootViewController.h"

@implementation RootViewController

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChildViewController *detailViewController = [[ChildViewController alloc] init];
    // Assign self as the delegate for the child view controller
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {

    // Do something with value...

    // ...then dismiss the child view controller
    [self.navigationController popViewControllerAnimated:YES];
}

@end

Hope this helps!

希望这可以帮助!

回答by Jhaliya

This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.

下面的代码仅显示了委托概念的非常基本的用法..您可以根据需要命名变量和类。

First you need to declare a protocol:

首先你需要声明一个协议:

Let's call it MyFirstControllerDelegate.h

我们称之为MyFirstControllerDelegate.h

@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end

Import MyFirstControllerDelegate.hfile and confirm your FirstControllerwith protocol MyFirstControllerDelegate

导入MyFirstControllerDelegate.h文件并使用MyFirstControllerDelegate协议确认您的FirstController

#import "MyFirstControllerDelegate.h"

@interface FirstController : UIViewController<MyFirstControllerDelegate>
{

}

@end

In the implementation file, you need to implement both functions of protocol:

在实现文件中,需要实现协议的两个功能:

@implementation FirstController 


    - (void) FunctionOne: (MyDataOne*) dataOne
      {
          //Put your finction code here
      }
    - (void) FunctionTwo: (MyDatatwo*) dataTwo
      {
          //Put your finction code here
      }

     //Call below function from your code
    -(void) CreateSecondController
     {
             SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
           //..... push second controller into navigation stack 
            mySecondController.delegate = self ;
            [mySecondController release];
     }

@end

in your SecondController:

在你的SecondController 中

@interface SecondController:<UIViewController>
{
   id <MyFirstControllerDelegate> delegate;
}

@property (nonatomic,assign)  id <MyFirstControllerDelegate> delegate;

@end

In the implementation file of SecondController.

SecondController的实现文件中。

@implementation SecondController

@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
   [delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
   [delegate FunctionTwo:myDataSecond];
}

@end

Hereis the wiki article on delegate.

是关于委托的维基文章。

回答by iOS Team

Following solution is very basic and simple approach to send data from VC2 to VC1 using delegate .

以下解决方案是使用 delegate 将数据从 VC2 发送到 VC1 的非常基本和简单的方法。

PS: This solution is made in Xcode 9.X and Swift 4

PS:此解决方案是在Xcode 9.X 和 Swift 4 中制作的

Declared a protocol and created a delegatevar into ViewControllerB

声明的协议并创建了一个代表变种成ViewControllerB

    import UIKit

    //Declare the Protocol into your SecondVC
    protocol DataDelegate {
        func sendData(data : String)
    }

    class ViewControllerB : UIViewController {

    //Declare the delegate property in your SecondVC
        var delegate : DataDelegate?
        var data : String = "Send data to ViewControllerA."
        override func viewDidLoad() {
            super.viewDidLoad()
        }

        @IBAction func btnSendDataPushed(_ sender: UIButton) {
                // Call the delegate method from SecondVC
                self.delegate?.sendData(data:self.data)
                dismiss(animated: true, completion: nil)
            }
        }

ViewControllerAconfirms the protocol and expected to receive data via delegate method sendData

ViewControllerA确认协议并期望通过委托方法sendData接收数据

    import UIKit
        // Conform the  DataDelegate protocol in ViewControllerA
        class ViewControllerA : UIViewController , DataDelegate {
        @IBOutlet weak var dataLabel: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
        }

        @IBAction func presentToChild(_ sender: UIButton) {
            let childVC =  UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"ViewControllerB") as! ViewControllerB
            //Registered delegate
            childVC.delegate = self
            self.present(childVC, animated: true, completion: nil)
        }

        // Implement the delegate method in ViewControllerA
        func sendData(data : String) {
            if data != "" {
                self.dataLabel.text = data
            }
        }
    }

回答by BDGapps

You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html

您需要使用委托和协议。这是一个带有示例的站点http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html