2012-02-14 3 views
0

내 앱이 질문을하고 질문에 따라 UITextField 또는 UISwitch를 배치합니다.Objective-C : UItextFields를 스크롤 오프 할 때 입력을 유지하고 태그 이름을 유지하는 방법은 무엇입니까?

사용자가 텍스트를 입력하면 자동으로 어떤 textField를 감지하고 그에 따라 텍스트를 배치합니다.

잘 작동하지만 항목을 스크롤 오프하면 사용자 입력과 태그 이름도 제거되며 그 위에 새로운 항목을 배치하는 영역이 표시됩니다.

그래서 사용자가 텍스트를 입력하면 이전 textField에 텍스트가 저장됩니다.

이 문제를 방지하는 방법을 알고 싶습니다.

의견이 있습니까? 미리 감사드립니다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
NSLog(@"-------------cellForRowAtIndexPath---------------"); 

cell_id = [qid objectAtIndex:[indexPath row] ];  
static NSString *CellIdentifier = @"Cell";  
label = nil; 
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    [self configureLabel];   
    [[cell contentView] addSubview:label]; 
} 

dict = [qtext objectAtIndex:[indexPath row]]; 
celltext = [NSString stringWithFormat:@"%@\n\n\n",[[dict allKeys] objectAtIndex:0]]; 
dict = [qtype objectAtIndex:[indexPath row]]; 
type = [[dict allKeys] objectAtIndex:0];  

//place the question 
cell.textLabel.text = celltext; 

    NSLog(@"celltext=%@",celltext); 
    if([type isEqualToString:@"devider"]){  
     [self configureDevider]; 
    }else{ 
     [self configureCell];  
    } 
    if([cell_id intValue] == ([qid count])){ 
    tabledone = @"Yes"; 
    } 

tableView.backgroundColor=[UIColor clearColor]; 
tableView.opaque=NO; 
tableView.backgroundView=nil; 

NSString *a = [arrAllheight objectAtIndex:[indexPath row]]; 


allheight +=thisheight; 
thisheight =[a intValue]; 



if([type isEqualToString:@"YN"]){ 

    DCRoundSwitch *ynSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220,thisheight-40,80,27)] ; 

    [email protected]"Yes"; 
    [email protected]"No"; 
    [answers addObject:ynSwitch]; 
    [cell addSubview:ynSwitch]; 
    [ynSwitch setTag:[cell_id intValue]]; 
    [ynSwitch addTarget:self action:@selector(setAnswersForRoundSwitches:) forControlEvents:UIControlEventValueChanged]; 

    i++; 


}else if([type isEqualToString:@"freetext"]){ 

    //When the done button was clicked, remove the keybords from the screen 
    [self makeTextField]; 

    [rtxtfield addTarget:self action:@selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit]; 
    // [rtxtfield value]; 



}else if([type isEqualToString:@"dropdown"]){ 

    picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:@"%d",cell_id]]; 

    //Choose an array for this textField 
    // [self getPickerArray]; 
    [self makeTextField]; 
    //[rtxtfield addTarget:self action:@selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit]; 

    //When the done button was clicked, remove the keybords from the screen 
    [rtxtfield addTarget:self action:@selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit]; 
    //Get the tag for picker 
    [rtxtfield addTarget:self action:@selector(getTag:) forControlEvents:UIControlEventTouchDown];  
    //Display picker 
    [rtxtfield addTarget:self action:@selector(acsheet:) forControlEvents:UIControlEventTouchDown];  
    //set Tag for the textField 
    [rtxtfield setTag:[cell_id intValue]]; 
     NSLog(@"rtxtfield tag=%d",rtxtfield.tag); 

} 


if([type isEqualToString:@"devider"]){ 
[self caliculateHeightofCell]; 
}else{ 
[self caliculateHeightofCell]; 
} 


return cell; 

} 
+0

uitableview를 사용하고 있습니까? – Radu

+0

예, 있습니다. 나는 그것을 언급하지 않아서 미안합니다. – user973067

+0

글쎄 문제는 셀 whit있을 수 있습니다. cellForRowAtIndexPath있는 if (cell == nil) {} 약간의 테스트를 수행하고 // if (cell == nil) {colom //} 그리고 그것이 작동하는지 확인하십시오. – Radu

답변

2

텍스트를 dataSource에 저장하십시오. UITableViewCells에는 상태 정보가 없어야합니다.

- (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]; 
     UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(2, 2, 200, 40)]; 
     textField.tag = 999; 
     textField.delegate = self; 
     textField.placeholder = @"Enter text here"; 
     [cell.contentView addSubview:textField]; 
    } 
    UITextField *textField = (UITextField *)[cell.contentView viewWithTag:999]; 
    textField.text = [self.dataSource objectAtIndex:indexPath.row]; 
    /* configure cell */ 
    return cell; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField { 
    UIView *contentView = [textField superview]; 
    UITableViewCell *cell = (UITableViewCell *)[contentView superview]; 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
    [self.dataSource replaceObjectAtIndex:indexPath.row withObject:textField.text]; 
} 

if (cell == nil)의 외부 뷰를 추가하지 마십시오 :이 비슷한을 구현

!
다른 셀 유형을 사용하는 경우 다른 CellIdentifier를 사용하십시오! 이처럼 :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *SwitchCellIdentifier = @"SwitchCell"; 
    static NSString *TextFieldCellIdentifier = @"TextFieldCell"; 

    UITableViewCell *cell = nil; 
    if (/* current cell is a text field cell */) { 
     cell = [tableView dequeueReusableCellWithIdentifier:TextFieldCellIdentifier]; 
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextFieldCellIdentifier]; 
      // add textField 
     } 
     // configure cell... 
    } 
    else if (/* current cell is a switch cell */) { 
     cell = [tableView dequeueReusableCellWithIdentifier:SwitchCellIdentifier]; 
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SwitchCellIdentifier]; 
      // add switch 
     } 
     // configure cell... 
    } 
    return cell; 
} 
+0

와우, 이걸 시도해 주셔서 감사 드리며 결과를 얻 자마자 알려 드리겠습니다.하지만 dataSource에 대한 더 많은 정보가 필요합니다. 나는 'qtext'라는 NSMutableArray를 만들었다. 그래서 당신의 코드에서 qtext를 dataSource로 사용할 수 있다는 것을 의미합니까? – user973067

+0

네, 내 코드의 데이터 소스는 NSMutableArray –

+0

입니다. 감사합니다. – user973067

-1

라벨 = 전무를 시도;

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

//if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    [self configureLabel];   
    [[cell contentView] addSubview:label]; 
//} 

코멘트 당신 같은 코드와 즉시이을 변경하면 데이터 모델 에 저장을

+0

고마워, 나는 그것을 시도했지만 작동하지 않습니다. 동일한 문제가 남아 있고 각 질문에 흰색 직사각형 배경이 나타납니다. 배경을 분명하게 설정했습니다. – user973067

+0

문제는 뷰가로드 될 때 cellForRowAtIndexPath가 두 번 호출되고 질문과 항목을 두 번 호출하는 것입니다. – user973067

+0

cellforrowatindexpath는 테이블에있는 행의 정확한 수에 대해 호출해야합니다. – Radu

3

하여 컨트롤의 상태를 어떻게되는지 말해. 그래서, 아마도 여러분의 모델은 일련의 질문이며, 각 질문은 해답을 담을 수있는 인스턴스 변수를 가지고 있습니다. 보기 컨트롤러는 테이블 데이터 원본과 테이블 대리자 일 가능성이 높기 때문에 셀의 모든 컨트롤 대상이되도록해야합니다. 즉, -tableView:cellForRowAtIndexPath:에 새 셀을 설정할 때 뷰 컨트롤러를 셀의 UITextField 또는 UISwitch 대상으로 만듭니다. 사용자가 이러한 컨트롤 중 하나를 변경하면 뷰 컨트롤러에서 액션이 트리거되고 뷰 컨트롤러는 컨트롤의 새 값을 검색하여 데이터 모델의 해당 질문에 저장할 수 있습니다.

이 방법을 사용하면 화면 밖으로 스크롤하는 것에 대해 걱정할 필요가 없습니다. 질문이 다시보기로 스크롤 되 자마자 해당 행에 대해 -tableView:cellForRowAtIndexPath:이 다시 호출되며 해당 셀을 다시 구성하는 데 필요한 모든 정보가 제공됩니다.

+0

이것은 매우 명확하고 많은 도움이되었습니다 감사합니다! – user973067

0

나는 문제를 해결하기 위해 일했다, 그러나 나는 마침내 바로를 가지고 : 그것은, DCRoundSwitch 및 pickerView TextField를 사용하고 원인 죄송합니다 그것이 긴 코드입니다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    NSLog(@"-----------------cellForRowAtIndexPath---------------");  

    Questions *q = [qtext objectAtIndex:indexPath.row]; 
    NSLog(@"question=%@",q.question); 
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    static NSString *SwitchCellIdentifier = @"SwitchCell"; 
    static NSString *TextFieldCellIdentifier = @"TextFieldCell"; 
    static NSString *DropDownFieldCellIdentifier = @"DropDownCell"; 

    cell = nil; 
    cell = [tableView dequeueReusableCellWithIdentifier:TextFieldCellIdentifier]; 
    if ([q.question_type isEqualToString:@"freetext"]) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextFieldCellIdentifier]; 

    if (cell == nil) { 
    [self makeTextField]; 
     [cell.contentView addSubview:rtxtfield];    
     cell.textLabel.text = q.question; 
     } 

    [self makeTextField]; 
    [self configureCell]; 
    [self configureLabel]; 

    cell.textLabel.text = q.question; 
    [cell.contentView addSubview:rtxtfield]; 


    rtxtfield.text = [appDelegate.dataSource objectAtIndex:indexPath.row]; 
    rtxtfield.tag=[indexPath row]; 



}else if([q.question_type isEqualToString:@"YN"]){ 
     AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SwitchCellIdentifier]; 

    if (cell == nil) { 
    [self makeDCRoundSwitch]; 
    [ynSwitch setTag:[indexPath row]]; 
    cell.textLabel.text = q.question; 
    [self configureLabel]; 
    [self configureCell]; 
    } 
    [self makeDCRoundSwitch]; 
    [ynSwitch setTag:[indexPath row]]; 
    cell.textLabel.text = q.question; 
    [self configureLabel];  
    [self configureCell]; 

    [ynSwitch addTarget:self action:@selector(ynSwitchDidEndEditing:) forControlEvents:UIControlEventValueChanged]; 
    if([[appDelegate.dataSource objectAtIndex:indexPath.row] isEqualToString:@"Yes"]){ 
     [ynSwitch setOn:YES animated:YES]; 
    } else{ 
     [ynSwitch setOn:NO animated:YES]; 
    } 

    rtxtfield.tag=[indexPath row];  


    } else if([q.question_type isEqualToString:@"dropdown"]){ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:DropDownFieldCellIdentifier]; 

    if (cell == nil) { 
     [self makeTextField]; 
     [cell.contentView addSubview:rtxtfield];    
     cell.textLabel.text = q.question; 
    } 

    [self makeTextField]; 
    [self configureCell]; 
    [self configureLabel]; 

    cell.textLabel.text = q.question; 
    [cell.contentView addSubview:rtxtfield]; 
    picc=q.question_array; 

    //When the done button was clicked, remove the keybords from the screen 
    [rtxtfield addTarget:self action:@selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit]; 
    //Get the tag for picker 
    [rtxtfield addTarget:self action:@selector(getTag:) forControlEvents:UIControlEventTouchDown];  
    //Display picker 
    [rtxtfield addTarget:self action:@selector(acsheet:) forControlEvents:UIControlEventTouchDown];  
    //set Tag for the textField 
    [rtxtfield setTag:[indexPath row]];  



    // AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    rtxtfield.text = [appDelegate.dataSource objectAtIndex:indexPath.row]; 
    rtxtfield.tag=[indexPath row]; 

} 


[self makeTextField]; 
rtxtfield.tag=[indexPath row]; 

tableView.backgroundColor=[UIColor clearColor]; 
tableView.opaque=NO; 
tableView.backgroundView=nil; 


return cell; 

} 
관련 문제