所以我有我的应用程序,并且有一个带有点击计数器和显示标签的 View 。我希望它在主视图上显示文本(现在是这样),但也在第二个 View 上显示文本。
那么我怎样才能在另一个 View 上显示文本呢?如果需要更多详细信息,请发送电子邮件。
重现点击计数器的步骤 .h 文件:
@interface Level1 : UIViewController {
int counter;
IBOutlet UILabel *count;
}
-(IBAction)plus;
@property (assign) int counter;
@end
.m 文件:
@synthesize counter;
- (void) viewDidLoad {
counter=1;
count.text = @"0";
[super viewDidLoad];
}
-(IBAction)plus {
counter=counter + 1;
count.text = [NSString stringWithFormat:@"%i",counter];
}
@end
提前致谢
最佳答案
您可以使用计数器值创建模型,该模型将在两个 View 之间共享。
模型通常使用单例模式创建。在这种情况下,可以这样做:
你的.h文件:
@interface CounterModel
@property (assign) NSInteger counter;// atomic
+ (id)sharedInstance;
- (void)increment;
@end
您的 .m 文件:
@implementation CounterModel
@synthesize counter;
- (id)init
{
if (self = [super init])
{
}
return self;
}
+ (id)sharedInstance
{
static CounterModel *instance = nil;
if (instance == nil)
{
instance = [[CounterModel alloc] init];
}
return instance;
}
- (void)increment
{
counter++;
}
@end
然后,您可以从一个 View Controller 调用:
[[CounterModel sharedInstance] increment];
从第二秒开始,您可以通过调用以下方式读取此更新值:
[[CounterModel sharedInstance] counter];
要实现您想要的效果,您可以在 viewWillAppear 方法中设置从模型的计数器值读取的 UILabel 值。
关于objective-c - 在两个 View 上显示来自点击计数器的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13000409/