2014-07-02 37 views
0

如何實現帶有textField的UITableViewCell?我在StackOverflow上經歷了一些類似的問題,但我發現其中大多數處理的情況是tableView的顯示總是不變的,並且確切地知道哪些值到了哪裏。對於我的實現,每個部分的行數和行數由用戶決定,可以是任何東西。我已經能夠在單元格中獲得textField,但是當我滾動表格並且單元格從視圖中消失時,我發現輸入的任何文本都會丟失。這是我到目前爲止添加一個UITextField,將其文本保留在UITableViewCell中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    UITextField *myTextField = [[UITextField alloc] 
          initWithFrame:CGRectMake(215, (cell.contentView.bounds.size.height-30)/2, 60, 30)]; 

    [myTextField setDelegate: self]; 
    myTextField.tag = indexPath.section; 
    NSLog(@"%ld", (long)myTextField.tag); 


    myTextField.placeholder = @"0%"; 
    myTextField.borderStyle = UITextBorderStyleRoundedRect; 

    [cell addSubview:myTextField]; 

    cell.textLabel.text = self.cellLabels[indexPath.section]; 
    return cell; 
} 

我知道問題是什麼,我只是無法找出解決辦法。即使我存儲了用戶以某種方式輸入數組中每個textField的所有內容,但由於cellForRowAtIndexPath被再次調用並且textField被重新繪製,因此當它從屏幕返回時,我無法爲每個字段設置文本。

這幾乎是我想要的,功能明智。但 「Paper1」 和 「Paper2」 可能是不同的部分...

This is pretty much what I want

回答

1

使用視圖模型。將每個單元格的文本存儲在數組中,然後在cellForRowAtIndexpath中設置文本。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    UITextField *myTextField = [[UITextField alloc] 
         initWithFrame:CGRectMake(215, (cell.contentView.bounds.size.height-30)/2, 60, 30)]; 

    [myTextField setDelegate: self]; 
    myTextField.tag = indexPath.section; 
    NSLog(@"%ld", (long)myTextField.tag); 

    myTextField.placeholder = @"0%"; 
    myTextField.borderStyle = UITextBorderStyleRoundedRect; 
    myTextField.text = [self textForCellAtIndexPath:indexPath]; 
    [cell addSubview:myTextField]; 

    cell.textLabel.text = self.cellLabels[indexPath.section]; 
    return cell; 

}問題的

+0

部分是文本是由用戶決定,我不能預測其輸入並存儲在數組中。 – Marcus

+1

我並不是建議你預測他們的意見。你需要存儲他們輸入的文本。由於某些原因,您沒有分享您的代表。現在您只需在輸入視圖模型中記錄文本。 – CrimsonChris

+0

基本上,不要將文本字段用作主文本存儲。使用視圖模型(字符串數組或者「論文」?)。 – CrimsonChris

相關問題