我喜欢做什么:
UITextField
中输入10,然后点按UIButton
。 UILabel
显示10,UITextField
显示为空白。 UITextField
中输入5,然后点按UIButton
。 UILable
显示15,UITextField
再次显示为空白。使用以下代码,我将保存输入的数字并显示在标签中,但是如何告诉数组添加并显示总数而不仅仅是我输入的第一个数字?
ħ
#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]];
}
答案 0 :(得分:0)
迭代数组,使用[string intValue]
将所有值作为数字,并在另一个变量中求和。然后使用格式化的字符串[NSString stringWithFormat: @"%d"]
将计算值添加到标签中。
答案 1 :(得分:0)
您需要遍历所有值并将其添加到运行总计中。看看这个: -
- (IBAction)saveNumber:(id)sender
{
[array addObject:self.field.text];
[NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
[field setText:@""];
// Create an enumerator from the array to easily iterate
NSEnumerator *e = [array objectEnumerator];
// Create a running total and temp string
int total = 0;
NSString stringNumber;
// Enumerate through all elements of the array
while (stringNumber = [e nextObject]) {
// Add current number to the running total
total += [stringNumber intValue];
}
// Now set the label to the total of all numbers
[label setText:[NSString stringWithFormat:@"%d",total];
}
我评论了代码的可读性。