Как суммировать содержимое многократно используемых пользовательских ячеек для табличного представления, которое действует как калькулятор - PullRequest
0 голосов
/ 01 августа 2011

Я построил табличное представление с ячейками настраиваемого табличного представления, где каждая ячейка имеет несколько полей UITextField, которые позволяют пользователю вводить числа, которые обеспечивают расчет. Ячейка имеет промежуточный итог UITextField, который предоставляет результат для этой ячейки.

Моя проблема в том, что я хочу взять промежуточный итог этой ячейки и каждой дополнительной ячейки, которую использует Пользователь, и предоставить итоговое значение для другого UIView.

Я не знаю, как взять значение каждого промежуточного итога для каждой ячейки, и, кроме того, как я могу узнать, сколько ячеек использовал пользователь, и все это для того, чтобы предоставить пользователю ИТОГО в другом виде ,

Каков наилучший способ достичь этого?

Вот код.

Я хочу добавить новые ячейки и иметь возможность добавлять их в расчет. Но каждая ячейка будет содержать разные значения, предоставленные пользователем.

Best! * * 1013

#import <UIKit/UIKit.h>


@interface ProCalculator : UIViewController <UITableViewDelegate, UITableViewDataSource>      {

UITextField *totalField;
UITextField *differenceField;

UITextField *productField;
UITextField *price1Field;
UITextField *discount1P1Field;
UITextField *discount2P1Field;
UITextField *subtotal1Field;

UITextField *product2Field;
UITextField *price2Field;
UITextField *discount1P2Field;
UITextField *discount2P2Field;
UITextField *subtotal2Field;

}

@property (nonatomic, retain) IBOutlet UITextField *totalField;
@property (nonatomic, retain) IBOutlet UITextField *differenceField;

@property (nonatomic, retain) IBOutlet UITextField *productField;
@property (nonatomic, retain) IBOutlet UITextField *price1Field;
@property (nonatomic, retain) IBOutlet UITextField *discount1P1Field;
@property (nonatomic, retain) IBOutlet UITextField *discount2P1Field;
@property (nonatomic, retain) IBOutlet UITextField *subtotal1Field;

@property (nonatomic, retain) IBOutlet UITextField *product2Field;
@property (nonatomic, retain) IBOutlet UITextField *price2Field;
@property (nonatomic, retain) IBOutlet UITextField *discount1P2Field;
@property (nonatomic, retain) IBOutlet UITextField *discount2P2Field;
@property (nonatomic, retain) IBOutlet UITextField *subtotal2Field;


-(IBAction)calculateDiscounts:(id)sender;
-(IBAction)removeKeyboard;


@end


#import "ProCalculator.h"
#import "ProductCell.h"


@implementation ProCalculator

@synthesize totalField, differenceField, productField, price1Field, discount1P1Field,     discount2P1Field, subtotal1Field;
@synthesize product2Field, price2Field, discount1P2Field, discount2P2Field, subtotal2Field;


-(IBAction)calculateDiscounts:(id)sender
{

//Calculate product 1 within first Cell

NSString *firstPrice = self.price1Field.text;
NSString *discount1P1 = self.discount1P1Field.text;
NSString *discount2P1 = self.discount2P1Field.text;

double subtotal1WithDiscount1;
double subtotal1WithDiscount2;
double firstPriceDouble = [firstPrice doubleValue];
double discount1P1Double = [discount1P1 doubleValue];
double discount2P1Double = [discount2P1 doubleValue];
double percentageDiscount1P1;
double percentageDiscount2P1;
double savings1P1;
double savings2P1;

percentageDiscount1P1 = discount1P1Double / 100; 
percentageDiscount2P1 = discount2P1Double / 100;
savings1P1 = firstPriceDouble * percentageDiscount1P1;
subtotal1WithDiscount1 = firstPriceDouble - savings1P1;
savings2P1 = subtotal1WithDiscount1 * percentageDiscount2P1;
subtotal1WithDiscount2 = subtotal1WithDiscount1 - savings2P1;

NSString *finalSubtotal1 = [[NSString alloc] initWithFormat:@"$ %.02f",   subtotal1WithDiscount2];

self.subtotal1Field.text = finalSubtotal1;


//Calculate product 2 within second Cell (Instead of Building more cells, I need to get information from User Input to create Cells and store information from them and add them to the calculation. 

NSString *secondPrice = self.price1Field.text;
NSString *discount1P2 = self.discount1P2Field.text;
NSString *discount2P2 = self.discount2P2Field.text;

double subtotal2WithDiscount1;
double subtotal2WithDiscount2;
double secondPriceDouble = [secondPrice doubleValue];
double discount1P2Double = [discount1P2 doubleValue];
double discount2P2Double = [discount2P2 doubleValue];
double percentageDiscount1P2;
double percentageDiscount2P2;
double savings1P2;
double savings2P2;

percentageDiscount1P2 = discount1P2Double / 100; 
percentageDiscount2P2 = discount2P2Double / 100;
savings1P2 = secondPriceDouble * percentageDiscount1P2;
subtotal2WithDiscount1 = secondPriceDouble - savings1P2;
savings2P2 = subtotal2WithDiscount1 * percentageDiscount2P2;
subtotal2WithDiscount2 = subtotal2WithDiscount1 - savings2P2;

NSString *finalSubtotal2 = [[NSString alloc] initWithFormat:@"$ %.02f", subtotal2WithDiscount2];

self.subtotal1Field.text = finalSubtotal2;



//Calculate Total

double totalAmount;
totalAmount = subtotal1WithDiscount2 + subtotal2WithDiscount2;
NSString *theTotal = [[NSString alloc] initWithFormat:@"$ %.02f", totalAmount];
self.totalField.text = theTotal;

//Calculate Money Saved

double moneySaved;
moneySaved = savings1P1 + savings2P1 + savings1P2 + savings2P2;
NSString *theMoneySaved = [[NSString alloc] initWithFormat:@"$ %.02f", moneySaved];
self.differenceField.text = theMoneySaved;


}

-(IBAction)removeKeyboard
{
[self.productField resignFirstResponder];
[self.price1Field resignFirstResponder];
[self.discount1P1Field resignFirstResponder];
[self.discount2P1Field resignFirstResponder];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)dealloc
{
[super dealloc];
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ProductTableViewCell";


ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSArray *topLabel = [[NSBundle mainBundle] loadNibNamed:@"ProductTableViewCell" owner:self options:nil];

    for (id currentObject in topLabel) {

        if ([currentObject isKindOfClass:[ProductCell class]]) {
            cell = (ProductCell *) currentObject;
            break;

        }

    }

}



return cell;
}





@end

1 Ответ

0 голосов
/ 01 августа 2011

Прежде всего, я предполагаю, что вы используете пользовательский UITableViewCell, текстовое поле которого является одним из его параметров.

Я бы предложил создать связанную модель с этими ячейками, в которой есть параметр, который сохраняет значение текстового поля каждый раз, когда пользователь вводит новую информацию. Что-то вроде:

@interface TableViewCellModel : NSObject {

  NSString * _valueOfTextfield;
}

@property (nonatomic, retain) NSString * valueOfTextfield;

@end

@implementation TableViewCellModel

@synthesize valueOfTextfield = _valueOfTextfield;

@end

Затем, когда текстовое поле нажимается, и пользователь вводит информацию и оставляет текстовое поле, обновляет связанную модель ячейки, чтобы сохранить значение текстового поля.

Если вы хотите показать ИТОГО текстовых полей во всех ячейках, просто посмотрите на каждую из ячеек, соответствующих моделям, и проверьте, имеет ли свойство valueOfTextfield ноль или нет.

Однако, одно предупреждение: если каждый из пользовательских UITableViewCells имеет свое собственное текстовое поле, у вас могут возникнуть проблемы с производительностью, а также с событиями касания в ячейках. Возможно, вы захотите использовать одноэлементный класс, который обрабатывает текстовые поля отдельно, и каждая из пользовательских ячеек имеет ссылку на этот одноэлементный класс.

РЕДАКТИРОВАТЬ: Я играл с некоторым кодом, и я думаю, что у меня есть то, что вы хотите сейчас. Вам понадобится несколько файлов, и это займет немного времени. Они будут в .h, затем .m парах.

@interface TableViewModel : NSObject {
  int _index;
  NSString * _textFieldValue;
}

@property (nonatomic, assign) int index;
@property (nonatomic, retain) NSString * textFieldValue;

@end

#import "TableViewModel.h"

@implementation TableViewModel

@synthesize index = _index;
@synthesize textFieldValue = _textFieldValue;

@end

Тогда

#import <UIKit/UIKit.h>
@class TableViewModel;

@interface TableViewCell : UITableViewCell {
  IBOutlet UILabel * _label;
}

@property (nonatomic, retain) TableViewModel * tableViewModel;

- (IBAction)useTextField;

@end

#import "TableViewCell.h"
#import "TableViewModel.h"
#import "AppDelegate.h"

@implementation TableViewCell

- (void)dealloc; {
    [super dealloc];
}

- (void)setTableViewModel:(TableViewModel *)tableViewModel; {
  _label.text = [tableViewModel textFieldValue];
}

- (TableViewModel *)tableViewModel; {
  return nil;
}

- (IBAction)useTextField; {
  [[AppDelegate appDelegate] useTextFieldForIndex:[self.tableViewModel index]];
}

@end

и, наконец,

#import <UIKit/UIKit.h>
@class TableViewCell;

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> {

  int _index;
  NSMutableArray * _items;
  IBOutlet TableViewCell * _cell;
  IBOutlet UITableView * _tableView;
  IBOutlet UITextField * _textField;
}

- (void)useTextFieldForIndex:(int)aIndex;

@end

#import "ViewController.h"
#import "TableViewModel.h"
#import "TableViewCell.h"

@implementation ViewController

- (void)dealloc; {
  [_items release];
  [super dealloc];
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad; {
  [super viewDidLoad];
  // This is an example of how to fill in the _items array with Models
  _items = [[NSMutableArray alloc] init];

  TableViewModel * model = [[TableViewModel alloc] init];
  model.textFieldValue = @"1";
  model.index = 0;

  [_items addObject:model];
  [model release];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField; {
  TableViewModel * model = [_items objectAtIndex:_index];
  model.textFieldValue = [_textField.text retain];
  [_items replaceObjectAtIndex:_index withObject:model];
  [_tableView reloadData];
  [_textField resignFirstResponder];
  return YES;
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
  return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
  return 100;//This should be whatever the height of the cell is!
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; {
  return [_items count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; {

  NSString * cellIdentifier = @"TableViewCell";
  TableViewCell * cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  if (cell == nil) {

    [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil]; // hooks up _cell for us
    cell = _cell;
  }

  cell.tableViewModel = ((TableViewModel *) [_items objectAtIndex:indexPath.row]);

  return cell;
}

- (void)useTextFieldForIndex:(int)aIndex; {
  _index = aIndex;
  [_textField becomeFirstResponder];
}

@end

Я предполагаю, что вы знаете, как подключить перья, но если вам нужна дополнительная помощь, просто спросите. Также вам необходимо добавить эти 2 метода в AppDelegate.

+ (AppDelegate *)appDelegate; {
  return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (void)useTextFieldForIndex:(int)aIndex; {
  [self.viewController useTextFieldForIndex:aIndex];
}

Это позволит AppDelegate передавать действия с действиями текстового поля только в одном контроллере представления. Это также должно помочь с производительностью. Чтобы пояснить, _items содержит все модели, которые используются в табличном представлении. (Примечание: если вы хотите, чтобы пользователь добавил новую ячейку, все, что вам нужно сделать, это добавить новую модель в этот массив.)

Действие: - (IBAction)useTextField; присоединено к кнопке очистки, и когда она нажата, она сообщает AppDelegate, чтобы сказать ViewController вызвать клавиатуру, и как только вы закончите с ней, вы обновите модель как индекс ячейки, которая была нажата, и перезагрузите представление таблицы.

Затем вы можете настроить ячейки так, как вам нужно, и убедиться, что вы подходите и к моделям.

Чтобы сложить значения в моделях, вам нужно только использовать:

double sum = 0;

for(TableViewCellModel * model in _items){
  sum += [model.valueOfTextfield doubleValue];
}

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...