2014-04-30 2 views
0

У меня есть табличный вид, где мне нужно отобразить текст вопроса и их тип ответа. Тип ответа может быть как UISwitch (single_option), UITextField (text_option), так и Star Rating View (star_option). Все вопросы и их тип ответа поступают с сервера. Поэтому для каждой строки таблицы мне нужно отобразить один текст вопроса и тип ответа, как я упомянул в приведенном ниже снимке экрана. Может быть n число вопросов, поэтому я установил их фрейм соответственно числу вопросов. Теперь моя проблема заключается в том, когда я просматриваю вверх или вниз, тогда вопрос отображается правильно, но их тип ответа идет случайным образом. И также я не получаю правильную высоту ячейки.UITableviewCell отображается неправильно во время прокрутки в ios

enter image description here

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
     Surveys *surveys = [[Surveys alloc] init]; 
     surveys = [arraySurveys objectAtIndex:indexPath.row]; 
     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *surveysCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (!surveysCell) { 
      surveysCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

      UILabel *lblSurveyQuestionText = nil; 
      SVSegmentedControl *segment1 = nil; 
      UITextField *tfAnswer = nil; 

      //For displaying Voting Questions 
      lblSurveyQuestionText = [[UILabel alloc] init]; 
      labelHeight = [self getLabelHeightForIndex:indexPath.row]; 

      lblSurveyQuestionText.frame = CGRectMake(10, 5, 300,labelHeight); 

      lblSurveyQuestionText.backgroundColor = [UIColor clearColor]; 
      lblSurveyQuestionText.text = surveys.questions; 
      lblSurveyQuestionText.textAlignment = NSTextAlignmentLeft; 
      lblSurveyQuestionText.lineBreakMode = NSLineBreakByWordWrapping; 
      lblSurveyQuestionText.numberOfLines = 0; 
      lblSurveyQuestionText.tag = 10; 
      [lblSurveyQuestionText sizeToFit]; 
      lblSurveyQuestionText.textColor = [UIColor whiteColor]; 

      [surveysCell.contentView addSubview:lblSurveyQuestionText]; 

      //For displaying UISwitch 
      NSArray *arrayOption1 = [[NSArray alloc] initWithObjects:@"Yes", @"No", nil]; 
      segment1 = [[SVSegmentedControl alloc] initWithSectionTitles:arrayOption1]; 

      segment1.thumb.tintColor = [UIColor colorWithRed:0.6 green:0.2 blue:0.2 alpha:1]; 

      segment1.changeHandler = ^(NSUInteger newIndex) { 
       NSString *selectedName = [arrayOption1 objectAtIndex:newIndex]; 
       NSLog(@"Switch selected answer is = %@", selectedName); 
      }; 

      segment1.center = CGPointMake(65, lblSurveyQuestionText.frame.size.height+27); 

      //For displaying text field 
      tfAnswer = [[UITextField alloc] init]; 
      CGRect frameRect = CGRectMake(10, lblSurveyQuestionText.frame.size.height+13, 300, 25); 
      frameRect.size.height = 25; 
      tfAnswer.frame = frameRect; 

      UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 7, 10)]; 
      tfAnswer.leftView = paddingView; 
      tfAnswer.leftViewMode = UITextFieldViewModeAlways; 
      tfAnswer.textColor = [UIColor colorWithRed:(59/255.0) green:(59/255.0) blue:(59/255.0) alpha:1.0]; 
      tfAnswer.delegate = self; 
      tfAnswer.font = [UIFont fontWithName:@"Helvetica Neue Medium" size:16.0]; 
      tfAnswer.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tf_301_23.png"]];\ 
      tfAnswer.returnKeyType = UIReturnKeyDone; 

      //For displaying star view 
      starRatingAnswer = [[TQStarRatingView alloc] initWithFrame:CGRectMake(10, lblSurveyQuestionText.frame.size.height+10, 180, 30) numberOfStar:5]; 
      starRatingAnswer.delegate = self; 

      surveysCell.selectionStyle = UITableViewCellSelectionStyleNone; 
      tblSurveys.tableFooterView = viewSurveysBottom; 

      NSLog(@"Surveys answer type is = %@", surveys.answer_type); 

      if ([surveys.answer_type isEqualToString:@"text_option"]) { 

       [surveysCell.contentView addSubview:tfAnswer]; 
      } 
      else if ([surveys.answer_type isEqualToString:@"single_option"]) { 

       [surveysCell.contentView addSubview:segment1]; 
      } 
      else{ 

       [surveysCell.contentView addSubview:starRatingAnswer]; 
      } 
      return surveysCell; 

     } 

     ((UILabel *)[surveysCell.contentView viewWithTag:10]).text = surveys.questions; 
     return surveysCell; 
} 

JSON:

{ 
    "Question_sq_details": [ 
     { 
      "event_sq_qns_id": 3, 
      "questions": "Effectiveness of the speakers", 
      "answer_type": "star_option" 
     }, 
     { 
      "event_sq_qns_id": 4, 
      "questions": "What is your primary job title/focus? Please select one.", 
      "answer_type": "single_option" 
     }, 
     { 
      "event_sq_qns_id": 5, 
      "questions": "Quality of the content", 
      "answer_type": "star_option" 
     }, 
     { 
      "event_sq_qns_id": 6, 
      "questions": "Usefulness of the Solutions Showcase", 
      "answer_type": "text_option" 
     }, 
     { 
      "event_sq_qns_id": 7, 
      "questions": "Relevance of the Solutions Showcase to your business", 
      "answer_type": "star_option" 
     }, 
     { 
      "event_sq_qns_id": 8, 
      "questions": "Relevance of the topics to your business", 
      "answer_type": "star_option" 
     }, 
     { 
      "event_sq_qns_id": 9, 
      "questions": "General Comments", 
      "answer_type": "text_option" 
     } 
    ] 
} 

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

Спасибо.

+1

использовать это для надежды Ful для и http://stackoverflow.com/questions/22862938/uitableviewcells-with-uibutton-overlaps-while-scrolling/22863122#22863122 –

+0

Большое спасибо @ Anbu.Karthik..now работает. Но можете ли вы рассказать мне, как я могу сохранить их все ответы на несколько строк. Мне нужно отправить ответ на сервер? – user2786

+0

может сказать, что ответ нужен –

ответ

0

У вас есть три типа ячеек, обрабатывайте их по-разному. И не забудьте использовать макросы препроцессора вместо простого номера как tag s.

#define lblSurveyQuestionTextTag 10 

BTW Я предпочитаю подклассифицировать UITableViewCell, чем испортить это.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    Surveys *surveys = [[Surveys alloc] init]; 
    surveys = [arraySurveys objectAtIndex:indexPath.row]; 

    // differenct identifiers based on different type of cells 
    static NSString *CellIdentifier = surveys.answer_type; 

    UITableViewCell *surveysCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (!surveysCell) { 
     // Setup shared property 
     surveysCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     surveysCell.selectionStyle = UITableViewCellSelectionStyleNone; 
     tblSurveys.tableFooterView = viewSurveysBottom; 

     UILabel *lblSurveyQuestionText = nil; 

     //For displaying Voting Questions 
     lblSurveyQuestionText = [[UILabel alloc] init]; 
     labelHeight = [self getLabelHeightForIndex:indexPath.row]; 

     lblSurveyQuestionText.frame = CGRectMake(10, 5, 300,labelHeight); 

     lblSurveyQuestionText.backgroundColor = [UIColor clearColor]; 
     lblSurveyQuestionText.text = surveys.questions; 
     lblSurveyQuestionText.textAlignment = NSTextAlignmentLeft; 
     lblSurveyQuestionText.lineBreakMode = NSLineBreakByWordWrapping; 
     lblSurveyQuestionText.numberOfLines = 0; 
     lblSurveyQuestionText.tag = 10; 
     [lblSurveyQuestionText sizeToFit]; 
     lblSurveyQuestionText.textColor = [UIColor whiteColor]; 

     [surveysCell.contentView addSubview:lblSurveyQuestionText]; 

     // end setup shared properties 

     if ([surveys.answer_type isEqualToString:@"text_option"]) { // setup text_option type 
     //For displaying text field 
      UITextField *tfAnswer = [[UITextField alloc] init]; 
      CGRect frameRect = CGRectMake(10, lblSurveyQuestionText.frame.size.height+13, 300, 25); 
      frameRect.size.height = 25; 
      tfAnswer.frame = frameRect; 

      UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 7, 10)]; 
      tfAnswer.leftView = paddingView; 
      tfAnswer.leftViewMode = UITextFieldViewModeAlways; 
      tfAnswer.textColor = [UIColor colorWithRed:(59/255.0) green:(59/255.0) blue:(59/255.0) alpha:1.0]; 
      tfAnswer.delegate = self; 
      tfAnswer.font = [UIFont fontWithName:@"Helvetica Neue Medium" size:16.0]; 
      tfAnswer.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tf_301_23.png"]];\ 
      tfAnswer.returnKeyType = UIReturnKeyDone; 
      tfAnswer.tag = 2555; 
      [surveysCell.contentView addSubview:tfAnswer]; 
     } 
     else if ([surveys.answer_type isEqualToString:@"single_option"]) { // setup single_option type 
      //For displaying UISwitch 
      NSArray *arrayOption1 = [[NSArray alloc] initWithObjects:@"Yes", @"No", nil]; 
      SVSegmentedControl *segment1 = [[SVSegmentedControl alloc] initWithSectionTitles:arrayOption1]; 

      segment1.thumb.tintColor = [UIColor colorWithRed:0.6 green:0.2 blue:0.2 alpha:1]; 

      segment1.center = CGPointMake(65, lblSurveyQuestionText.frame.size.height+27); 

      segment1.changeHandler = ^(NSUInteger newIndex) { 
      NSString *selectedName = [arrayOption1 objectAtIndex:newIndex]; 
      NSLog(@"Switch selected answer is = %@", selectedName); 
     }; 

     segment1.tag = 2556; 
     [surveysCell.contentView addSubview:segment1]; 
    } 
    else{ // setup star type 
     //For displaying star view 
     /* TQStarRatingView * */starRatingAnswer = [[TQStarRatingView alloc] initWithFrame:CGRectMake(10, lblSurveyQuestionText.frame.size.height+10, 180, 30) numberOfStar:5]; 
     starRatingAnswer.delegate = self; 
     starRatingAnswer.tag = 2557; 
     [surveysCell.contentView addSubview:starRatingAnswer]; 
     } 
    } 

    if ([surveys.answer_type isEqualToString:@"text_option"]) { 
     UITextField *tfAnswer = (UITextField*)[surveysCell.contentView viewWithTag:2555]; 
     // tfAnswer.text = @"" 
    } 
    else if ([surveys.answer_type isEqualToString:@"single_option"]) { 
     SVSegmentedControl *segment1 = (SVSegmentedControl*)[surveysCell.contentView viewWithTag:2556]; 
     // segment1.selectedIndex = 1; 
    } 
    else{ 
     TQStarRatingView *starRatingAnswer = (TQStarRatingView*)[surveysCell.contentView viewWithTag:2557]; 
     // starRatingAnswer.stars = 5; 
    } 

    // NSlog cause performance loss in TableView, turn it off when not needed or release/adhoc builds 
    NSLog(@"Surveys answer type is = %@", surveys.answer_type); 

    ((UILabel *)[surveysCell.contentView viewWithTag:10]).text = surveys.questions; 
    return surveysCell; 
} 
Смежные вопросы