从子类视图重新加载标签视图文本

时间:2013-05-17 05:13:59

标签: iphone objective-c xcode class label

我有一个视图控制器类First.h / First.m,其中我在.h文件中有一个名为-(void)ChangeLabelName:(NSString *)title defined的方法。

(in First.m)
-(void)ChangeLabelName:(NSString *)title
{
    NSLog(@"in set label");
    [topheading_label setText:title];
}

现在我有第二个名为Second.h / Second.m的视图控制器类。我将这个视图控制器作为子视图添加到第一个视图控制器,如 -

(in First.m)
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
Second *second = [storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.view addSubview:second.view];

在second.m中,我有一个名为- (void)call_summary:(id)sender的方法     (现在在Second.m)

- (void)call_summary:(id)sender
{
    NSLog(@"in call summary click");
    First *first=[[First alloc] init];
    [first ChangeLabelName:@"My name is shivam"];
}

这是方法-(void)ChangeLabelName:(NSString *)title.但是标签文字没有变化。 我使用[topheading_label setNeedsDisplay];.但是dint对我有用。 帮助我。

3 个答案:

答案 0 :(得分:1)

您的标签未更新的原因是因为您是第二个

- (void)call_summary:(id)sender

没有引用正确的控制器实例。

First *first=[[First alloc] init];

创建了一个新的第一个实例。

如果你想让第二次与第一次交谈,你可以使用委托。

在Second.h中,定义一个类似

的协议
@protocol SecondDelegate <NSObject>
-(void)ChangeLabelName:(NSString *)title;
@end

添加新属性:

@property (nonatomic, strong) id <SecondDelegate> delegate;

在First.h中,

@interface First : UIViewController <SecondDelegate>

在First.m

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle: nil];
Second *second = [storyboard instantiateViewControllerWithIdentifier:@"second"];
second.delegate = self;
[self.view addSubview:second.view];

在Second.m callSummary:

- (void)call_summary:(id)sender
{
  NSLog(@"in call summary click");    
  [self.delegate ChangeLabelName:@"My name is shivam"];
}

有关Protocal的更多信息,请参阅this

BTW,我建议你在Instance方法中使用小写字母作为前缀,例如:changeLabelName。

答案 1 :(得分:1)

您可以使用NotificationCenter。在First.m中注册通知并从Second.m发布通知。

答案 2 :(得分:0)

方法1

我建议您在FirstappDelegate中声明synthesize视图控制器。

AppDelegate.h

@property (nonatomic,strong) First *first;

AppDelegate.m

first=[[First alloc] init];

现在在你的Second.m

- (void)call_summary:(id)sender
{
    AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];

    [appDelegate.first ChangeLabelName:@"My name is Rajneesh :D "];
}  

方法2

- (void)call_summary:(id)sender
{
    NSUserDefaults *def =[NSUserDefaults standardUserDefaults];
    [def setObject:@"My name is Rajneesh :D " forKey:@"lablString"];
}  

Second's viewWillAppear中设置您的文字。

-(void)viewWillAppear:(BOOL)animated
{
    yourLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"lablString"];
}

方法3

使用protocol,查看Kenny的回答

相关问题