【问题标题】:Updating ViewController UILabel from another class从另一个类更新 ViewController UILabel
【发布时间】:2015-08-31 07:59:53
【问题描述】:

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

我想从另一个类更新 ViewController 中的 UILabel。 这是一个我无法开始工作的小演示程序。 我有一个具有 3 个 UILabel 的视图控制器,一个是从 viewDidLoad 更新的,另外两个我想从另一个名为 Hello 的类更新,该类是从 ViewController 调用的,我可以看到该类作为控制台被正确调用正在记录 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

你好.h

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

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

你好.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

【问题讨论】:

  • 你每次都在分配一个全新的 ViewController。
  • 请查看 NSNotification 或委托。
  • 我明白了,感谢您的快速回复。我将重新审视我的代码。
  • @Larme 感谢您的指出。
  • @Matz 非常感谢您提供的信息,这些主题对我帮助很大。

标签: ios objective-c iphone uiviewcontroller


【解决方案1】:

Hello类的第一个更新方法

+ (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";
}

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多