簡體   English   中英

如何在不使用prepareForSegue的情況下為類設置委托

[英]How to set up a delegate to a class without the use of prepareForSegue

我有兩堂課,我希望他們彼此交談。 類A包含tableView,當用戶點擊表格行時,我將啟動didSelectRowAtIndexPath方法。 在這種方法中,我需要通過委托將此通知B類。 我知道委托的工作方式,但是很難確定如何在不使用prepareForSegue方法的情況下設置A的委托。

通常,我在設置代表時會這樣做

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"goToManipulator"]) {
        ManipulatorViewController *secondVC = (ManipulatorViewController *) segue.destinationViewController;
        [secondVC setDelegate:self];
    }
}

但是,如何在不使用prepareForSegue的情況下設置委托?

提前致謝

編輯:

這就是我的情節提要的結構。 “接收器”視圖控制器是一種獲取數據並顯示在“當前名稱”標簽中的視圖控制器,具體取決於從“發送者”視圖控制器(最靠近右側)在表視圖中選擇的內容。

http://oi62.tinypic.com/2li99w1.jpg

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ManipulatorViewController *secondVC = [[ManipulatorViewController alloc] init...];
    [secondVC setDelegate:self];

    //if you use push transition in UINavigationController
    [self.navigationController pushViewController:secondVC animated:YES];

    //if you use modal transition
    [self presentViewController:secondVC animated:YES completion:nil]
}

init...表示初始化取決於您的程序體系結構。

編輯

如果要從情節secondVC中獲取secondVC ,請使用

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ManipulatorViewController* secondVC = [storyboard instantiateViewControllerWithIdentifier:@"secondVC"];

並且不要忘記在故事板中為viewController添加標識符。

我了解您的用例是這樣的:

在接收器中,打開發件人。 在此處選擇一個值,選擇完該值后,您要告訴接收者新值。

您可以在Receiver實現的Sender上創建協議。 然后,在捕獲Sender中選定值的函數中,調用協議方法(例如didSelectNewName()或其他方法)。

當然,您需要一個Receiver的句柄,通常通過委托獲得它。 但是,如果您使用segue或其他方法從Receiver過渡到Sender,則您都將有機會設置Sender的代理。

如果這不是您想要的內容,請確切說明您如何初始化發送方,以及為什么不希望使用segue。

輕按A的單元格時,View Controller B是否已實例化? 如果是這樣,並且您沒有使用prepareForSegue來獲取另一個View Controller的身份,則最好使用NSNotification Center。 在View Controller A的didSelectRowAtIndex方法中,您可以將

[[NSNotificationCenter defaultCenter] postNotificationName:@"yourNotificationName" object:nil userInfo:dictionaryWithYourData];

它將向您的整個應用發出通知,告知您已選擇該行。 如果您事先使用任何想要的信息來初始化字典,則可以通過userInfo傳遞字典。 然后,在View Controller B的viewDidLoad中,添加

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethod:) name:@"yourNotificationName" object:nil];

讓它監聽通知。 您設置的選擇器將接受NSNotification作為參數,因此您可以按以下方式獲取字典:

- (void)yourMethod:(NSNotification *)notification
{
    NSDictionary *yourData = [notification userInfo];
}

這是我的工作。

在.m文件中:

@implementation ViewController{

   SecondViewController *svc;

}

接下來,您需要執行以下操作:

- (IBAction)goToView2:(id)sender {
    if (!svc) {
        svc = [[self storyboard] instantiateViewControllerWithIdentifier:@"View2"];
        [svc setDelegate:self];
    }
    [[self navigationController] pushViewController:svc animated:YES];
}

只需確保在StoryBoard中將正確的標識符設置為聲明了協議的ViewController。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM