从另一个 class 更新 ViewController UILabel

Updating ViewController UILabel from another class

我是开发新手,一直在尝试解决这个问题,但是在尝试了各种不同的解决方案之后,我仍然无法获得我想要的结果。

我想从另一个 class 更新 ViewController 中的 UILabel。 这是一个我无法开始工作的小演示程序。 我有一个视图控制器,它有 3 个 UILabel,一个是从 viewDidLoad 更新的,另外两个我想从另一个 class 更新,称为 Hello,它是从 ViewController 调用的,我可以看到class 被正确调用,因为控制台正在记录 NSLog 条目,但我无法获得更新 UILabel 的语法。

提前致谢。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, retain) IBOutlet UILabel *firstLabelBox;
@property (nonatomic, retain) IBOutlet UILabel *secondLabelBox;
@property (nonatomic, retain) IBOutlet UILabel *thirdLabelBox;

@end

ViewController.m

#import "ViewController.h"
#import "Hello.h"
@interface ViewController ()

@end


@implementation ViewController

@synthesize firstLabelBox;
@synthesize secondLabelBox;
@synthesize thirdLabelBox;

- (void)viewDidLoad {
[super viewDidLoad];

firstLabelBox.text=@"Hello";

[Hello updatedisplay];
[Hello getStringToDisplay];

 }
@end

Hello.h

#import <Foundation/Foundation.h>
@class ViewController;
@interface Hello : NSObject

+(void)updatedisplay;
+(void) getStringToDisplay;
@end

Hello.m

#import "Hello.h"
#import "ViewController.h"


@implementation Hello

+ (void)updatedisplay
{

 NSLog(@"NewClass - updatedisplay");
 ViewController *labelupdate02 = [[ViewController alloc]init];
 labelupdate02.secondLabelBox.text = @"Apple";
}

+ (void) getStringToDisplay
{
NSLog(@"Inside getString function - updatedisplay");
ViewController *labelupdate03 = [[ViewController alloc]init];
labelupdate03.thirdLabelBox.text = @"World";
}

@end

Hello的第一次更新方法class

+ (void)updatedisplay
{
    NSLog(@"NewClass - updatedisplay");    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_SECOND_LABEL" object:nil];
}

+ (void) getStringToDisplay
{
    NSLog(@"Inside getString function - updatedisplay");    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGE_THIRD_LABEL" object:nil];
}

然后更新viewDidLoad()

- (void)viewDidLoad 
{
    [super viewDidLoad];
    firstLabelBox.text=@"Hello";

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

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

    [Hello updatedisplay];
    [Hello getStringToDisplay];
}

ViewController.m.

中实现以下方法
- (void)secondLabel
{
    secondLabelBox.text = @"Apple";
}

- (void)thirdLabel
{
    thirdLabelBox.text = @"World";
}