ios-協(xié)議/代理是怎么實(shí)現(xiàn)兩個頁面之間傳值


  • 第一頁面
    //NextViewController是push進(jìn)入的第二個頁面
    //NextViewController.h 文件
    //定義一個協(xié)議,前一個頁面ViewController要服從該協(xié)議,并且實(shí)現(xiàn)協(xié)議中的方法
@protocol NextViewControllerDelegate <NSObject>
 - (void)passTextValue:(NSString *)tfText;
@end
@interface NextViewController : UIViewController
@property (nonatomic, assign) id<NextViewControllerDelegate> delegate;
@end

//NextViewController.m 文件
//點(diǎn)擊Button返回前一個ViewController頁面

- (IBAction)popBtnClicked:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(passTextValue:)]) {
        //self.inputTF是該頁面中的TextField輸入框
        [self.delegate passTextValue:self.inputTF.text];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
  • 傳到第一頁
    • 接下來我們在看看ViewController文件中的內(nèi)容,
      //ViewController.m 文件
@interface ViewController ()<NextViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *nextVCInfoLabel;
@end

//點(diǎn)擊Button進(jìn)入下一個NextViewController頁面

- (IBAction)btnClicked:(id)sender
{
    NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
    nextVC.delegate = self;//設(shè)置代理
    [self.navigationController pushViewController:nextVC animated:YES];
}

//實(shí)現(xiàn)協(xié)議NextViewControllerDelegate中的方法

#pragma mark - NextViewControllerDelegate method
- (void)passTextValue:(NSString *)tfText
{
    //self.nextVCInfoLabel是顯示NextViewController傳遞過來的字符串Label對象
    self.nextVCInfoLabel.text = tfText;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容