objective-c - 在两个 View 上显示来自点击计数器的文本

标签 objective-c ios xcode4.5

所以我有我的应用程序,并且有一个带有点击计数器和显示标签的 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/

相关文章:

objective-c - 如果一个类支持包含同名属性的协议(protocol),会发生什么情况?

xcode - 应用程序仅在 iOS 6 中旋转,而不在 iOS 5 中旋转

iphone - 如何使用 Objective C 从 Cocoa 中的 WebFrame 获取跨度值

objective-c - 是否有 iTunes Connect Game Center REST API?

ios - AdMob 原生高级广告单元 ID

ios - SwiftUI:用于通用(macOS 和 iOS) View 的 UserInterfaceSizeClass

c++ - 继承 - 符号未定义 Objective-C++

ios - UICollectionView单元格图像错误

ios - NSDateFormatter 在 swift 和 iOS SDK 8.0 中返回 nil

ios - UIStoryboard 应用程序中的 PopToViewController