2015-12-03 51 views
0

我在2個單元格內創建了2個文本框。桌面單元格內的ios textfield

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 
    } 
    if (indexPath.row == 0) { 
     [self CustomTextField:cell :txtFirstName]; 
     txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"]; 
     [cell addSubview:txtFirstName]; 
     txtFirstName.tag = 100; 
    } 
    else (indexPath.row == 1){ 
     [self CustomTextField:cell :txtLastName]; 
     txtLastName.text = [_dictInfoOneUser objectForKey:@"lastname"]; 
     [cell addSubview:txtLastName]; 
     txtLastName.tag = 101; 
    } 
} 

我想我設置了txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"];。我編輯了單元格的名字,之後,我滾動,它是刷新單元格並重置我在textfield中編輯的內容。

如何解決此問題。

************編輯

-(void)CustomTextField :(UITableViewCell *)cell :(UITextField *)textField{ 
    //add bottom border 
    CALayer *border = [CALayer layer]; 
    border.borderColor = [UIColor grayColor].CGColor; 
    border.frame = CGRectMake(cell.frame.size.width/2 - 160, textField.frame.size.height - 1, textField.frame.size.width, textField.frame.size.height); 
    border.borderWidth = 1; 
    [textField.layer addSublayer:border]; 
    textField.layer.masksToBounds = YES; 
    [textField setTextAlignment:NSTextAlignmentCenter]; 
} 
+0

有保存編輯信息?如果不是 - 比單元格中只有'默認'文本。 – Oleshko

+0

可能會將編輯後的文本保存到NSMutableArray中(每次編輯時都要刪除並添加),並使用此可變數組來填充單元格。當您滾動時,tableview被重新加載。 – enzo

+0

你可以編輯我的代碼嗎? –

回答

0

這是由於孔複用。遵循的格局是有條件地構建的子視圖(所以你只能得到一個單元格),但無條件地配置他們。像這樣...

if (indexPath.row == 0) { 
    UITextField *txtFirstName = (UITextField *)[cell viewWithTag:100]; 
    if (!txtFirstName) { 
     // it doesn't exist. build it 
     [self CustomTextField:cell :txtFirstName]; // not sure what this does, assuming it's part of building it 
     [cell addSubview:txtFirstName]; 
     txtFirstName.tag = 100; 
    } 
    // whether it was just built or not, give it a value 
    txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"]; 
} 
// same idea for the other row/textfield 
+0

它不適用於我:( –

+2

抱歉,這種方法是正確的,但我認爲問題與CustomTextField字段方法有關,請將該代碼添加到您的問題中 – danh

+0

編輯我的代碼 –

1

看來你不dequeing擺在首位你的,這裏是你的

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

應該是什麼樣子:你

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 
    } 
... 
} 
+0

'deque'-ing是初始化單元格的現代方法,但不是OP問題的原因,OP正在獲取一個單元格,如果沒有單元格,問題將出現異常,而不是單元格內容顯示不正確。 – danh