我喜欢做什么:
- 用户输入 10
UITextField
并点击UIButton
。 UILabel
显示 10 并UITextField
变为空白。- 用户输入 5
UITextField
并点击UIButton
。 UILable
显示 15 并UITextField
再次变为空白。
使用以下代码,我可以将输入的数字保存并显示在标签中,但是如何告诉数组添加并显示总数,而不仅仅是我输入的第一个数字?
H
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UILabel *label;
@property (nonatomic, strong) IBOutlet UITextField *field;
@property (nonatomic, strong) NSString *dataFilePath;
@property (nonatomic, strong) NSString *docsDir;
@property (nonatomic, strong) NSArray *dirPaths;
@property (nonatomic, strong) NSFileManager *fileMgr;
@property (nonatomic, strong) NSMutableArray *array;
- (IBAction)saveNumber:(id)sender;
@end
米
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize label, field, dataFilePath, docsDir, fileMgr, dirPaths, array;
- (void)viewDidLoad
{
[super viewDidLoad];
fileMgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFilePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"data.archive"]];
if ([fileMgr fileExistsAtPath:dataFilePath])
{
array = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath];
self.label.text = [array objectAtIndex:0];
}
else
{
array = [[NSMutableArray alloc] init];
}
}
- (IBAction)saveNumber:(id)sender
{
[array addObject:self.field.text];
[NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
[field setText:@""];
[label setText:[array objectAtIndex:0]];
}