2014-10-05 7 views
0

Когда я нажимаю кнопку в одной строке, кнопка в другом ряду исчезает. Почему это может произойти?UIButton исчезает после нажатия кнопки

Я рассмотрел следующий вопрос и все остальные вопросы в нем, но ничего не ответил на мою проблему.

Я использовал Debug Color Blended Layers, чтобы увидеть, если это просто цвет вещь, но моя кнопка только, кажется, полностью исчезает. Я подозревал, что это была вещь button.hidden, поэтому я жестко закодировал button.hidden = NO;, но ничего не изменилось.

Что поделал не так?

Таблица управления Код:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if ([locationObjectsArray count] > 0) 
    { 
     return [locationObjectsArray count]+1; 
    } 
    else 
     return 1; 
} 

// Populate the Table View with member names 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier= @"Cell"; 

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

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    // Configure the Cell... 
    UIButton *selectButton = (UIButton *)[cell viewWithTag:1]; 
    UILabel *cityNamesText = (UILabel *)[cell viewWithTag:2]; 
    UIButton *editButton = (UIButton *)[cell viewWithTag:3]; 

    //NSLog(@"[locationObjectsArray count]: %lu", (unsigned long)[locationObjectsArray count]); 

    if (indexPath.row >= [locationObjectsArray count]) { 
     // locationObjectsArray count == 0; Empty Array 
     cityNamesText.text = @"Add New Location"; 

     NSLog(@"%ld: %@", (long)indexPath.row, @"Add New Location"); 
     editButton.hidden = NO; 
     [editButton setTitle:@"Add" forState:UIControlStateNormal]; 
     //[editButton setTitle:@"Add" forState:UIControlStateApplication]; 
     selectButton.hidden = YES; 
    } 
    else if ([locationObjectsArray count] > 0) { 
     LocationObject *locObject = [locationObjectsArray objectAtIndex:indexPath.row]; 
     NSLog(@"%ld: %@", (long)indexPath.row, [locObject getLocationName]); 
     cityNamesText.text = [locObject getLocationName]; 
     selectButton.hidden = NO; 
     editButton.hidden = NO; 
    } 

    // Assign button tags 
    selectButton.tag = indexPath.row; 
    editButton.tag = indexPath.row; 

    [selectButton addTarget:self action:@selector(selectButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [editButton addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

    LocationObject *selectedLocationObject = [self loadLocationObjectWithKey:@"locObject"]; 
    // Set Selected Cell to different Color 
    if ([cityNamesText.text isEqualToString:[selectedLocationObject getCityName]]) { 
     // Change to lightBlue color 
     UIColor * lightBlue = [UIColor colorWithRed:242/255.0f green:255/255.0f blue:254/255.0f alpha:1.0f]; 
     [cell setBackgroundColor:lightBlue]; 
    } 
    else 
    { 
     // All non-selected cells are white 
     //[cell setBackgroundColor:[UIColor whiteColor]]; 
     //editButton.hidden = NO; 
    } 

    return cell; 
} 

// Select Button Clicked method 
-(void)selectButtonClicked:(UIButton*)sender 
{ 
    if ([locationObjectsArray count] == 0) 
    { 
     NSLog(@"locObject count == 0"); 
     // locationObjectsArray count == 0; Empty Array 
     // City name input is invalid 
     UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"No Locations Set" 
                 message:@"Please add a new location." 
                 delegate:self 
               cancelButtonTitle:@"OK" 
               otherButtonTitles: nil]; 
     [alert show]; 
    } 
    else 
    { 
     NSLog(@"locObject count > 0"); 
     if (sender.tag >= locationObjectsArray.count) { 
      // Create local isntance of the selected locationObject 
      LocationObject *locObject = [locationObjectsArray objectAtIndex:sender.tag]; 
      // Set locObject as current default locObject 
      [self saveLocationObject:locObject key:@"locObject"]; 
     } 


     [mainTableView reloadData]; 
    } 
} 

// Edit Button Clicked method 
-(void)editButtonClicked:(UIButton*)sender 
{ 
    if ([locationObjectsArray count] == 0) { 
     // locationObjectsArray count == 0; Empty Array 
     UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"Add Location" 
                 message:@"Input City Name" 
                 delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles: nil]; 
     alert.alertViewStyle = UIAlertViewStylePlainTextInput; 
     [alert addButtonWithTitle:@"Save"]; 
     [alert show]; 
    } 
    else 
    { 
     selectedObjectInArray = sender.tag; 
     UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"Edit Location" 
                 message:@"Input City Name" 
                 delegate:self 
               cancelButtonTitle:@"Cancel" 
               otherButtonTitles: nil]; 
     alert.alertViewStyle = UIAlertViewStylePlainTextInput; 
     [alert addButtonWithTitle:@"Save"]; 
     [alert show]; 
    } 
} 

// Handle alertView 
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{ 
    if ([alertView.title isEqualToString:@"Add Location"]) { 
     // Add Location Alert View 
     if (buttonIndex == 0) 
     { 
      NSLog(@"You have clicked Cancel"); 
     } 
     else if(buttonIndex == 1) 
     { 
      NSLog(@"You have clicked Save"); 
      UITextField *cityNameTextField = [alertView textFieldAtIndex:0]; 
      NSString *saveLocationName = cityNameTextField.text; 
      NSLog(@"saveLocationName: %@", saveLocationName); 
      if ([self isLocationValid:saveLocationName] == YES) { 
       NSLog(@"location is valid. locationObjectsArray.count = %lu", locationObjectsArray.count); 
       if (locationObjectsArray.count == 0) { 
        locationObjectsArray = [NSMutableArray array]; 
       } 
       // City name input is valid 
       LocationObject *locObject = [[LocationObject alloc] init]; 
       [locObject setCityName:saveLocationName]; 
       locObject.byCityName = YES; 
       [locationObjectsArray addObject:locObject]; 

       NSLog(@"After addObject: locationObjectsArray.count = %lu", locationObjectsArray.count); 

       [self saveLocationArrayObject:locationObjectsArray key:@"locationObjectsArray"]; 
       [mainTableView reloadData]; 
      } 
      else 
      { 
       // City name input is invalid 
       UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"City Name Invalid" 
                   message:@"Unable to locate input city." 
                   delegate:self 
                 cancelButtonTitle:@"OK" 
                 otherButtonTitles: nil]; 
       [alert show]; 
      } 
     } 
    } 
    else if ([alertView.title isEqualToString:@"Edit Location"]) 
    { 
     // Edit Location Alert View 
     if (buttonIndex == 0) 
     { 
      NSLog(@"You have clicked Cancel"); 
     } 
     else if(buttonIndex == 1) 
     { 
      NSLog(@"You have clicked Save"); 
      UITextField *cityNameTextField = [alertView textFieldAtIndex:0]; 
      NSString *saveLocationName = cityNameTextField.text; 
      if ([self isLocationValid:saveLocationName]) { 
       // City name input is valid 
       int selectedIndex = (int)selectedObjectInArray; 
       LocationObject *locObject = [locationObjectsArray objectAtIndex:selectedIndex]; 
       [locObject setCityName:saveLocationName]; 
       [locObject setByCityName:(Boolean *)TRUE]; 
       [locationObjectsArray setObject:locObject atIndexedSubscript:selectedIndex]; 
       [self saveLocationArrayObject:locationObjectsArray key:@"locationObjectsArray"]; 
       [mainTableView reloadData]; 
      } 
      else 
      { 
       // City name input is invalid 
       UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"City Name Invalid" 
                   message:@"Unable to locate input city." 
                   delegate:self 
                 cancelButtonTitle:@"OK" 
                 otherButtonTitles: nil]; 
       [alert show]; 
      } 
     } 
    } 

} 

До:

Edit button is visible

После выбора кнопки проверки:

Edit button is gone

+0

Можете ли вы разместить код? – YogevSitton

+0

OK обновлено с помощью tableView code @godmoney – erad

+0

Возможно, у вас возникла проблема с тем, как вы используете теги. Вы получаете ссылку на кнопки, обнаруживая представления с тегами 1, 2 и 3, но позже вы устанавливаете теги двух из этих кнопок на основе indexPath.row. Обычно вы делаете одно или другое из них, но не то, и другое. Лично мне действительно не нравится находить взгляды на основе их тегов. Я всегда создаю собственный класс ячеек и даю свои представления IBOutlets. Это чище и делает ваш код более читаемым. – rdelmar

ответ

2

Ваш вопрос в этих строках в cellForRowAtIndexPath:

// Assign button tags 
selectButton.tag = indexPath.row; 
editButton.tag = indexPath.row; 

Теги будут замешаны при повторном использовании ячеек, я бы рекомендовал пропустить использование тегов в этой ситуации и использовать, например. IBOutlets как @rdelmar указал.

Смежные вопросы