0

我有一个视图控制器和一个类(我正在使用情节提要)。如何 UILabel从类中更改(在视图控制器中)的文本?我试过这个,但无济于事:

ViewController *mainView = [[ViewController alloc] init];
[mainView view];

[mainView.progressBar setProgress:integer animated:YES];

NSLog(@"Updated Progress Bar");

NSString *progressLabelText = [NSString stringWithFormat:@"%@ out of %i followers", userString, [self.followers count]];

[mainView.progressLabel setText:progressLabelText];

NSLog(@"Updated Progress Label Text: %@", progressLabelText);

使用此代码不会更改文本。我应该怎么做?

编辑:ViewController 的 .h 文件中的进度条和标签如下所示:

@property (nonatomic, strong) IBOutlet UIProgressView *progressBar;
@property (nonatomic, strong) IBOutlet UILabel *progressLabel;

它们在 Interface Builder 中完全链接在一起。

4

4 回答 4

3

尝试使用通知来更新标签文本。

在您的 viewController 中写下:

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


  and selector is :
   -(void)updateLabel
{
    self.lblObject.text = @"Your updated text"
}

现在在您的班级中使用 Post 通知调用它:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"lblUpdate" object:nil];

记住使用相同的通知名称“lblUpdate”

于 2013-01-07T15:00:34.947 回答
3

用于或之间。delegate_messagingclassesviewcontrollers

请参阅协议和代表链接的基础知识。

于 2013-01-07T13:16:31.993 回答
0

但是使用 adelegate来做回调。在您的spamchecker.h添加中:

@protocol SpamCheckerDelegate <NSObject>
-(void)updateText:(NSString*)newText;
@end

@property (nonatomic, weak) id <SpamCheckerDelegate> delegate;

spamchecker.m您需要的地方添加:

[self.delegate updateText:@"newText"];

然后在你的mainView.h添加:

@interface MainView : UIViewController <SpamCheckerDelegate>

在您的mainview.m添加中:

spamchecker.delegate = self;

并实现如下方法:

-(void)updateText:(NSString*)newText
{
    [self.progressLabel setText:progressLabelText];
}
于 2013-01-07T13:12:36.513 回答
0

只是属性合成字符串,然后在类的viewWillAppear:方法中设置该字符串ViewController.m

只需NSString在文件中获取变量,ViewController.h如下所示..

@property (nonatomic, retain) NSString *progressText;

synthesize这在文件中, ViewController.m如下所示..

@synthesize progressText;

之后,在viewDidLoad:方法中只需在开始时设置文本,progressLableText如下所示......

- (void)viewDidLoad
{

     progressText = @"Your Text";
     [progressLabel setText:progressText];

}

并在viewWillAppear:上面设置文本...

- (void)viewWillAppear:(BOOL)animated
{
    [progressLabel setText:progressText];
}

并在您的代码中更改如下内容..

ViewController *mainView = [[ViewController alloc] init];
[mainView view];

[mainView.progressBar setProgress:integer animated:YES];

NSLog(@"Updated Progress Bar");

NSString *progressLabelText = [NSString stringWithFormat:@"%@ out of %i followers", userString, [self.followers count]];

mainView.progressText = progressLabelText;
[mainView.progressText retain];


NSLog(@"Updated Progress Label Text: %@", progressLabelText);

我希望这对你有帮助......

于 2013-01-07T13:21:36.133 回答