2015-01-06 3 views
1

Я создаю экран «X». В этом окне я создаю UITextField и после изменения «TextColor» и «Font» этого UITextField. Однако, когда я иду на экран «Y» и возвращаюсь к экрану «X» с использованием модального сегмента UITextField, теряют настройки, полные «TextColor» и «Font». Как я могу решить эту проблему?UITextField теряет настройки

спасибо!

EditaCanalTVVC.m

BOOL firstTime; 

@interface EditaCanalTVVC() 

@property (strong, nonatomic) IBOutlet UIView *viewNumCanal; 
@property (strong, nonatomic) IBOutlet UITextField *txtNumCanal; 
@property (strong, nonatomic) IBOutlet UILabel *lblNumCanal; 
@property (strong, nonatomic) IBOutlet UIView *viewTudo; 
@property (strong, nonatomic) IBOutlet UITableView *tableView; 
@property (strong, nonatomic) IBOutlet UIBarButtonItem *botaoCancelar; 
@property (strong, nonatomic) IBOutlet UIBarButtonItem *botaoOK; 

- (IBAction)btnCancelar:(id)sender; 
- (IBAction)btnOK:(id)sender; 

@end 

@implementation EditaCanalTVVC 
{ 
    NSString *strNomeCanal; 
    NSString *strNumCanal; 
    NSString *strDelay; 
} 

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

    } 
    return self; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (void)viewWillAppear:(BOOL)animated 
{  
    [self updateScreen]; 
    [self.tableView reloadData]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    firstTime = YES; 

    [self.txtNumCanal setTextColor: [UIColor darkGrayColor]]; 
    [self.txtNumCanal setFont:[UIFont fontPrincipal:17]]; 

    self.tableView.dataSource = self; 
    self.tableView.delegate = self; 

    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; 
    self.tableView.alwaysBounceVertical = NO; 

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; 

    // Initialization code 
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)]; 
    numberToolbar.barStyle = UIBarStyleBlackOpaque; 
    numberToolbar.items = [NSArray arrayWithObjects: 
          [[UIBarButtonItem alloc]initWithTitle:@"Cancelar" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)], 
          [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], 
          [[UIBarButtonItem alloc]initWithTitle:@"OK" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)], 
          nil]; 
    [numberToolbar sizeToFit]; 
    self.txtNumCanal.inputAccessoryView = numberToolbar; 

    UITapGestureRecognizer *tapGestureDimmer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toqueViewNumCanal:)]; 
    tapGestureDimmer.numberOfTapsRequired = 1; 
    [self.viewNumCanal addGestureRecognizer:tapGestureDimmer]; 


} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [self updateScreen]; 
} 

- (void)viewDidLayoutSubviews 
{ 
    self.viewTudo.backgroundColor = [UIColor corFundoCinza]; 
    self.navigationController.navigationBar.barTintColor = [UIColor corFundoCinza]; 

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) 
     [self.tableView setSeparatorInset:UIEdgeInsetsZero]; 

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) 
     [self.tableView setLayoutMargins:UIEdgeInsetsZero]; 

    [self updateScreen]; 
} 

- (void)updateScreen 
{  
    self.txtNumCanal.delegate = self; 

    if (self.addCanal) 
    { 
     if (firstTime) 
     { 
      self.nome_canal = @"Selecione o canal"; 
      self.delay = @"Selecione o delay"; 
      self.num_canal = @"Digite o número"; 
      firstTime = NO; 
     } 
    } 

    self.lblNumCanal.text = @"Número"; 
    self.lblNumCanal.textColor = [UIColor corLabelClaro]; 
    self.viewNumCanal.backgroundColor = [UIColor whiteColor]; 
    self.txtNumCanal.text = [NSString stringWithFormat:@"%@", self.num_canal]; 
    [self.txtNumCanal setTextColor: [UIColor darkGrayColor]]; 
    [self.txtNumCanal setFont:[UIFont fontPrincipal:17]]; 
} 

#pragma mark - Toques nas imagens de edição 

- (void)toqueViewNumCanal:(UITapGestureRecognizer *)sender 
{ 
    if (sender.state == UIGestureRecognizerStateRecognized) 
    { 
     [self.txtNumCanal becomeFirstResponder]; 
    } 
} 

#pragma mark - Eventos do TextField 

-(void)cancelNumberPad 
{ 
    [self.txtNumCanal resignFirstResponder]; 
    self.txtNumCanal.text = self.num_canal; 
} 

-(void)doneWithNumberPad 
{ 
    [self.txtNumCanal resignFirstResponder]; 

    if ([self.txtNumCanal.text isEqualToString:@""]) 
     self.txtNumCanal.text = self.num_canal; 
    else 
     self.num_canal = self.txtNumCanal.text; 

    [self updateScreen]; 
} 

#pragma mark - Eventos da Tabela 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 2; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier1 = @"CellCanal"; 
    static NSString *CellIdentifier3 = @"CellDelay"; 

    UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1]; 
    UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier3]; 

    int isCellCustom = 0; 

    if (!cell1) 
     cell1 = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier1]; 

    if (!cell3) 
     cell3 = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier3]; 

    switch (indexPath.row) 
    { 
     case 0: 
     { 
      isCellCustom = 1; 
      cell1.textLabel.text = @"Canal"; 
      cell1.detailTextLabel.text = [NSString stringWithFormat:@"%@", self.nome_canal]; 
      cell1.detailTextLabel.textColor = [UIColor darkGrayColor]; 

     } break; 

     case 1: 
     { 
      isCellCustom = 2; 
      cell3.textLabel.text = @"Delay"; 
      cell3.detailTextLabel.text = [NSString stringWithFormat:@"%@", self.delay]; 
      cell3.detailTextLabel.textColor = [UIColor darkGrayColor]; 

     } break; 
    } 

    cell1.textLabel.textColor = [UIColor corLabelClaro]; 
    [cell1 setBackgroundColor:[UIColor whiteColor]]; 

    cell3.textLabel.textColor = [UIColor corLabelClaro]; 
    [cell3 setBackgroundColor:[UIColor whiteColor]]; 

    if (isCellCustom == 1) 
     return cell1; 
    else 
     return cell3; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    switch (indexPath.row) 
    { 
     case 0: 
     { 
//   [self performSegueWithIdentifier:@"segueListaCanaisTV" sender:nil]; 

      UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
      ListaCanaisTVVC *lista = [storyboard instantiateViewControllerWithIdentifier:@"listaCanaisTV"]; 

      lista.tipoDaLista = 1; 

      [self presentViewController:lista animated:YES completion:nil]; 

     } break; 

     case 1: 
     { 


     } break; 

     default: 
      break; 
    } 

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return YES; 
} 

#pragma mark - Botões 

- (IBAction)btnCancelar:(id)sender 
{ 
    [self.navigationController popViewControllerAnimated:YES]; 
} 

- (IBAction)btnOK:(id)sender 
{ 
    [self.navigationController popViewControllerAnimated:YES]; 
} 

#pragma mark - UIStoryBoardSegue 

//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
//{  
// if ([segue.identifier isEqualToString:@"segueListaCanaisTV"]) 
// { 
//  ListaCanaisTVVC *list = (ListaCanaisTVVC *)segue.destinationViewController; 
//   
//  list.tipoDaLista = 1; 
//   
// }  
//} 

@end 

EditaCanalTVVC.h

#import <UIKit/UIKit.h> 

@interface EditaCanalTVVC : UIViewController <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> 

@property (nonatomic) int id_canal_local; 
@property (nonatomic) int id_canal_tv; 
@property (nonatomic) NSString *nome_canal; 
@property (nonatomic) NSString *num_canal; 
@property (nonatomic) NSString *delay; 

@property (nonatomic) int id_dispositivo; 

@property (nonatomic) BOOL addCanal; 
@property (nonatomic) BOOL canalSelecionado; 

- (void)updateScreen; 

@end 
+0

Как и где вы создаете этот UITextField? –

+0

UITextField создается из StoryBoard в UIViewController –

+0

, переместите код в viewDidLoad. viewWillAppear вызывается каждый раз, когда отображается основной вид VC, так что после каждого segue на VC вызывается 'updateScreen', что необязательно, так как эти параметры нужно установить только один раз. если вы хотите быть на 100% уверенным, что текст останется, укажите его в переменной экземпляра и сохраните его до тех пор, пока вам не понадобится его изменить. –

ответ

0

Попытка удалить self performSegue в файле .m и управлять им с помощью раскадровки вместо этого.

Для этого выберите свою кнопку и в Инспекторе соединений (стрелка по кругу) определите свой сегмент через часть Triggered Segue: оставьте точку на Y viewController и определите ее как «Present modally» (как " Modal "устарел).

Когда вы будете использовать кнопку, появится Y viewController, для этого вам не нужно кодировать одну строку.

Я также пытался сделать это по-своему, с кодированным segue, но я не могу воспроизвести ошибку (событие с sender:self на performSegue).

+0

Проблема в том, что мне нужно использовать 'self performSegue', потому что мне нужно отправить переменную как параметр. По этой причине я не смог применить ваше решение. Вы знаете другой способ решить эту проблему? Я буду очень благодарен. –

0

Ok, так что если вам нужно отправить переменные в качестве параметра, почему бы вам не попробовать это:

- (IBAction)didTapButton:(UIButton *)sender{ 
    SecondView *secondView = [[SecondView alloc] initWithNibName:@"SecondView" bundle:nil]; 
    secondView.someProperty = @"someValue"; 
    [self presentViewController:secondView animated:YES completion:nil]; 
} 

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

Если вы используете раскадровку, сделать это, чтобы получить secondView:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
SecondView *secondView = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"]; 

Затем вернуться к первой точки зрения, поставить этот код на второй взгляд:

[self dismissViewControllerAnimated:YES completion:nil]; 
+0

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

+0

Можете ли вы изменить свой вопрос и скопировать/вставить весь свой код в него, чтобы я мог взглянуть на все это? –

+0

Хорошо, я отредактирую. –