Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
This is my controller and how I'm using LMFormerField.
//
// LMCadastrarViewController.m
// DailyBaby
//
// Created by Lucas Moreira on 03/07/13.
// Copyright (c) 2013 Lucas Moreira. All rights reserved.
//
#import "LMCadastrarViewController.h"
#import "LMFormerField.h"
#import "LMFormerSelector.h"
#import "LMFormerServerUniquenessField.h"
@interface LMCadastrarViewController ()
@end
@implementation LMCadastrarViewController
@synthesize textFields, accessoryToolbar, previousField, nextField, closeField, currentIndex, datePicker, onSignup;
- (void)signup
{
BOOL isValid = TRUE;
NSMutableArray *errors = [NSMutableArray array];
for (id object in self.textFields) {
if ([[object class] isSubclassOfClass:[LMFormerField class]]) {
LMFormerField *field = object;
if (![field isValid]) {
isValid = NO;
if (field.errors != nil)
[errors addObject:[field.errors componentsJoinedByString:@", "]];
}
} else if ([[object class] isSubclassOfClass:[LMFormerServerUniquenessField class]]) {
LMFormerServerUniquenessField *field = object;
if (![field isValid]) {
isValid = NO;
if (field.currentMessage == nil || [field.currentMessage isEqualToString:@""])
[errors addObject:[NSString stringWithFormat:@"O campo \"%@\" não foi preenchido.", field.fieldIdentifier]];
else
[errors addObject:field.currentMessage];
}
}
}
if (isValid) {
NSString *password = [(LMFormerField *)self.textFields[8] value];
NSString *password_confirmation = [(LMFormerField *)self.textFields[9] value];
if ([password isEqualToString:password_confirmation]) {
NSString *name = [(LMFormerField *)self.textFields[0] value];
NSString *last_name = [(LMFormerField *)self.textFields[1] value];
NSString *username = [(LMFormerServerUniquenessField *)self.textFields[2] value];
NSString *email = [(LMFormerServerUniquenessField *)self.textFields[3] value];
NSString *grandfather = [(LMFormerField *)self.textFields[4] value];
NSString *grandmother = [(LMFormerField *)self.textFields[5] value];
NSString *birthday = [(LMFormerField *)self.textFields[6] value];
NSString *born_at = [(LMFormerField *)self.textFields[7] value];
NSNumber *sex = [(LMFormerSelector *)self.textFields[10] value];
NSNumber *private = [(LMFormerSelector *)self.textFields[11] value];
//user[ :email, :father, :mother, :birthday, :password, :password_confirmation, :sex, :is_private ]
NSDictionary *params = @{ @"user[name]": name, @"user[last_name]": last_name, @"user[username]": username, @"user[email]": email, @"user[father]": grandfather, @"user[mother]": grandmother, @"user[birthday]": birthday, @"user[born_at]": born_at, @"user[password]": password, @"user[password_confirmation]": password_confirmation, @"user[sex]": sex, @"user[is_private]": private };
self.view.userInteractionEnabled = NO;
self.navigationItem.leftBarButtonItem.enabled = NO;
self.navigationItem.rightBarButtonItem.enabled = NO;
[SVProgressHUD showWithStatus:@"Criando conta..."];
[[LMWebService shared] postPath:@"signup"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[SVProgressHUD dismiss];
self.view.userInteractionEnabled = YES;
self.navigationItem.leftBarButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem.enabled = YES;
if (onSignup) {
[self dismissViewControllerAnimated:YES completion:^ {
onSignup(@{ @"authToken": responseObject[@"auth_token"], @"username": username, @"password": password });
}];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
self.view.userInteractionEnabled = YES;
self.navigationItem.leftBarButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem.enabled = YES;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
[self displayErrorString:json[@"error"]];
}];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erros no formulário"
message:@"A confirmação de senha não confere com a senha"
delegate:nil cancelButtonTitle:@"Cancelar" otherButtonTitles:nil];
[alert show];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erros no formulário"
message:[errors componentsJoinedByString:@"\n"]
delegate:nil cancelButtonTitle:@"Cancelar" otherButtonTitles:nil];
[alert show];
}
}
- (void)goToPreviousField
{
if (currentIndex == 0)
[self closeCurrentField];
else {
self.currentIndex -= 1;
UITextField *textField = self.textFields[currentIndex];
[textField becomeFirstResponder];
}
[self updateButtons];
}
- (void)goToNextField
{
if (self.currentIndex == 8)
[self closeCurrentField];
else {
self.currentIndex += 1;
UITextField *textField = self.textFields[self.currentIndex];
[textField becomeFirstResponder];
}
[self updateButtons];
}
- (void)updateButtons
{
if (self.currentIndex == 0) {
nextField.enabled = YES;
previousField.enabled = NO;
} else if (self.currentIndex == 8) {
nextField.enabled = NO;
previousField.enabled = YES;
} else {
nextField.enabled = YES;
previousField.enabled = YES;
}
}
- (void)closeCurrentField
{
[self.view endEditing:YES];
self.currentIndex = -1;
}
- (void)birthdayChanged
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
LMFormerField *birthday = self.textFields[6];
birthday.text = [dateFormatter stringFromDate:datePicker.date];
}
- (void)keyboardWillDisappear:(NSNotification *)notification
{
self.currentIndex = -1;
}
- (void)close
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"Cadastrar";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Voltar" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Concluir" style:UIBarButtonItemStyleDone target:self action:@selector(signup)];
accessoryToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
previousField = [[UIBarButtonItem alloc] initWithTitle:@"Voltar" style:UIBarButtonItemStyleBordered target:self action:@selector(goToPreviousField)];
nextField = [[UIBarButtonItem alloc] initWithTitle:@"Próximo" style:UIBarButtonItemStyleBordered target:self action:@selector(goToNextField)];
closeField = [[UIBarButtonItem alloc] initWithTitle:@"Fechar" style:UIBarButtonItemStyleBordered target:self action:@selector(closeCurrentField)];
accessoryToolbar.items = @[ previousField, nextField, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], closeField ];
datePicker = [[UIDatePicker alloc] init];
[datePicker setDatePickerMode:UIDatePickerModeDate];
[datePicker setMaximumDate:[NSDate date]];
[datePicker addTarget:self action:@selector(birthdayChanged) forControlEvents:UIControlEventValueChanged];
BetweenLengths name_bet_in = { 2, 60 };
LMFormerField *name = [LMFormerField new];
name.label = @"Nome *";
name.fieldIdentifier = @"Nome";
name.formerDelegate = self;
name.placeholder = @"Insira seu nome";
name.inputAccessoryView = accessoryToolbar;
name.validations = @{
@"presence": @{ },
@"in": @{ @"value": [NSValue value:&name_bet_in withObjCType:@encode(BetweenLengths)] }
};
LMFormerField *last_name = [LMFormerField new];
last_name.label = @"Sobrenome";
last_name.fieldIdentifier = @"Sobrenome";
last_name.formerDelegate = self;
last_name.placeholder = @"Insira seu sobrenome";
last_name.inputAccessoryView = accessoryToolbar;
last_name.validations = @{
@"maxlength": @{ @"value": @(60) }
};
LMFormerServerUniquenessField *username = [LMFormerServerUniquenessField new];
username.label = @"Usuário *";
username.fieldIdentifier = @"Usuário";
username.formerDelegate = self;
username.placeholder = @"http://dailybaby.com.br/seu-username";
username.inputAccessoryView = accessoryToolbar;
username.requestPath = @"users/validateUsername";
username.autocorrectionType = UITextAutocorrectionTypeNo;
username.autocapitalizationType = UITextAutocapitalizationTypeNone;
LMFormerServerUniquenessField *email = [LMFormerServerUniquenessField new];
email.label = @"E-mail *";
email.fieldIdentifier = @"E-mail";
email.formerDelegate = self;
email.placeholder = @"Seu e-mail";
email.inputAccessoryView = accessoryToolbar;
email.requestPath = @"users/validateEmail";
email.autocorrectionType = UITextAutocorrectionTypeNo;
email.autocapitalizationType = UITextAutocapitalizationTypeNone;
email.keyboardType = UIKeyboardTypeEmailAddress;
LMFormerField *grandfather = [LMFormerField new];
grandfather.label = @"Nome do avô dos seus filhos";
grandfather.fieldIdentifier = @"Avô";
grandfather.formerDelegate = self;
grandfather.placeholder = @"Nome do avô dos seus filhos";
grandfather.inputAccessoryView = accessoryToolbar;
LMFormerField *grandmother = [LMFormerField new];
grandmother.label = @"Nome da avó dos seus filhos";
grandmother.fieldIdentifier = @"Avó";
grandmother.formerDelegate = self;
grandmother.placeholder = @"Nome do avó dos seus filhos";
grandmother.inputAccessoryView = accessoryToolbar;
LMFormerField *birthday = [LMFormerField new];
birthday.label = @"Data de aniversário";
birthday.fieldIdentifier = @"Data de aniversário";
birthday.formerDelegate = self;
birthday.inputAccessoryView = accessoryToolbar;
birthday.inputView = datePicker;
LMFormerField *born_at = [LMFormerField new];
born_at.label = @"Cidade que nasceu";
born_at.fieldIdentifier = @"Cidade que nasceu";
born_at.formerDelegate = self;
born_at.placeholder = @"São Paulo, SP (exemplo)";
born_at.inputAccessoryView = accessoryToolbar;
BetweenLengths password_bet_in = { 8, 128 };
LMFormerField *password = [LMFormerField new];
password.label = @"Senha *";
password.fieldIdentifier = @"Senha";
password.formerDelegate = self;
password.placeholder = @"Digite sua senha";
password.inputAccessoryView = accessoryToolbar;
password.secureTextEntry = YES;
password.validations = @{
@"presence": @{ },
@"in": @{ @"value": [NSValue value:&password_bet_in withObjCType:@encode(BetweenLengths)] },
};
LMFormerField *password_confirm = [LMFormerField new];
password_confirm.label = @"Confirmar *";
password_confirm.fieldIdentifier = @"Confirmar senha";
name.formerDelegate = self;
password_confirm.placeholder = @"Confirme sua senha";
password_confirm.inputAccessoryView = accessoryToolbar;
password_confirm.secureTextEntry = YES;
password_confirm.validations = @{
@"presence": @{ },
@"in": @{ @"value": [NSValue value:&password_bet_in withObjCType:@encode(BetweenLengths)] },
};
LMFormerSelector *sex = [LMFormerSelector new];
sex.label = sex.fieldIdentifier = @"Sexo";
[sex setOptions:@[ @"Masculino", @"Feminino" ]];
LMFormerSelector *private = [LMFormerSelector new];
private.label = private.fieldIdentifier = @"Conta privada";
[private setOptions:@[ @"Não", @"Sim" ]];
self.textFields = @[ name, last_name, username, email, grandfather, grandmother, birthday, born_at, password, password_confirm, sex, private ];
[self updateButtons];
[self birthdayChanged];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
NSLog(@"MANO, ESSE É O PROBLEMA!!");
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.textFields.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// NSLog(@"RETORNANDO CELL");
id textField = self.textFields[indexPath.row];
cell.textLabel.text = [textField label];
cell.textLabel.numberOfLines = 2;
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.accessoryView = textField;
NSLog(@"[FIM DE UPDATES] RETORNANDO CELL (%@)", NSStringFromClass([textField class]));
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([[cell.accessoryView class] isSubclassOfClass:[UITextField class]]) {
[(UITextField *)cell.accessoryView becomeFirstResponder];
}
}
#pragma mark UITextField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
// NSLog(@"COMEÇOU ESSE DELEGATE AQUI Ó: textFieldDidBeginEditing");
for (int index = 0, length = self.textFields.count; index < length; index++) {
id object = self.textFields[index];
if ([[object class] isSubclassOfClass:[UITextField class]] && [object isFirstResponder])
self.currentIndex = index;
}
// NSLog(@"ACABOU ESSE DELEGATE AQUI Ó: textFieldDidBeginEditing (%@)", NSStringFromClass([self.textFields[self.currentIndex] class]));
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.