我想在有人在模態視圖中進行更改後更新父視圖中的UILabel。所以,他們點擊「保存」後,新輸入的值會改變在父視圖控制器上顯示的文本。試圖更新父視圖控制器上的UILabel時解除模態視圖
但是,我似乎無法得到該UILabel刷新新輸入的值。
關於我可以嘗試的任何想法?我已經嘗試了一些東西,但是當視圖已經加載時,沒有任何東西正在被「刷新」。
謝謝!
我想在有人在模態視圖中進行更改後更新父視圖中的UILabel。所以,他們點擊「保存」後,新輸入的值會改變在父視圖控制器上顯示的文本。試圖更新父視圖控制器上的UILabel時解除模態視圖
但是,我似乎無法得到該UILabel刷新新輸入的值。
關於我可以嘗試的任何想法?我已經嘗試了一些東西,但是當視圖已經加載時,沒有任何東西正在被「刷新」。
謝謝!
有很多方法可以做到這一點。一種方法是使用NSNotificationCenter
能夠在不同類別之間進行呼叫。因此,在父視圖,你將有專人負責更新功能(允許調用它updateLabel),您將執行以下操作:
- (void) updateLabel
{
yourLabel.text = @"what you need";
}
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:@"DoUpdateLabel" object:nil];
}
現在,在其他視圖只是張貼在保存按鈕的通知:
[[NSNotificationCenter defaultCenter] postNotificationName:@"DoUpdateLabel" object:nil userInfo:nil];
編輯: 我要在這裏提到兩兩件事:
[[NSNotificationCenter defaultCenter] removeObserver:self];
詳細說明我的評論。這是我將如何實現委託方法來更新標籤。
在父視圖控制器的標題:
#import "ModalViewController.h"
@interface ViewController : UIViewController <ModalViewControllerDelegate>
/* This presents the modal view controller */
- (IBAction)buttonModalPressed:(id)sender;
@end
並在實施:
/* Modal view controller did save */
- (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text
{
NSLog(@"Update label: %@", text);
}
/* Prepare for segue */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"modalSegue"])
{
ModalViewController *mvc = (ModalViewController *) segue.destinationViewController;
mvc.delegate = self;
}
}
/* Present modal view */
- (IBAction)buttonModalPressed:(id)sender
{
[self performSegueWithIdentifier:@"modalSegue" sender:self];
}
這裏你可以看到在頂部的委派方法。
模態視圖控制器的報頭將包含委託協議這樣的:
@protocol ModalViewControllerDelegate;
@interface ModalViewController : UIViewController
@property (nonatomic, weak) id <ModalViewControllerDelegate> delegate;
- (IBAction)buttonSavePressed:(id)sender;
@end
@protocol ModalViewControllerDelegate <NSObject>
- (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text;
@end
模態視圖控制器的實施將包含類似於此的方法:
/* Save button was pressed */
- (IBAction)buttonSavePressed:(id)sender
{
if ([self.delegate respondsToSelector:@selector(modalViewControllerDidSave:withText:)])
[self.delegate modalViewControllerDidSave:self withText:@"Some text"];
[self dismissModalViewControllerAnimated:YES];
}
當按下保存按鈕,通知委託並通過委託方法發送文本視圖中的文本。
到resomve的NSNotificationCenter
您在主視圖中使用:
ParentViewController:
func updateLabel() {
yourLabel.text! = "what you need"
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.updateLabel), name: "DoUpdateLabel", object: nil)
}
在奧瑟維尤:
@IBAction func closePopUp(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName("DoUpdateLabel", object: nil, userInfo: nil)
}
我會制定一個授權方法。當按下「保存」按鈕時,模式將被解除,調用委託方法。父視圖實現了這種委託方法,並且在調用它時刷新標籤。 – simonbs 2012-01-18 21:06:00