如何设置一个简单的委托,以便在两个视图控制器之间进行通信?我有两个UITableViewControllers并需要使用委托将子视图控制器的值传递给父控件。我知道什么是代表,我只想看到一个简单的榜样。谢谢
3 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
@protocol MyFirstControllerDelegate- (void) FunctionOne: (MyDataOne*) dataOne;- (void) FunctionTwo: (MyDatatwo*) dataTwo;@end
#import "MyFirstControllerDelegate.h"@interface FirstController : UIViewController<MyFirstControllerDelegate>{}@end
@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
@interface SecondController:<UIViewController>{ id <MyFirstControllerDelegate> delegate;}@property (nonatomic,assign) id <MyFirstControllerDelegate> delegate;@end
@implementation SecondController@synthesize delegate;//Call below two function on self.-(void) SendOneDataToFirstController{ [delegate FunctionOne:myDataOne];}-(void) SendSecondDataToFirstController{ [delegate FunctionTwo:myDataSecond];}@end
浮云间
TA贡献1829条经验 获得超4个赞
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) } }
ViewControllerA
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 } } }
- 3 回答
- 0 关注
- 515 浏览
添加回答
举报
0/150
提交
取消