如何設置一個簡單的委托,以便在兩個視圖控制器之間進行通信?我有兩個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 關注
- 548 瀏覽
添加回答
舉報
0/150
提交
取消
