2011-04-25 89 views
2

我有一個UITableView與幾個UITableViewCells和這些單元格內的UITextFields。我實現了一個用於在不同文本域之間切換的UIToolbar。我可以轉到下一個單元格中的下一個文本框或前一個文本框。這工作正常,直到一個單元格應該成爲當前在tableview中不可見的第一響應者。UITableView scrollToRowAtIndexPath有時只滾動

我想通了

[self.tableview cellForRowAtIndexPath:indexPath] 

nil返回和手動滾動到與文本字段的細胞,其應該成爲第一響應,刪除該問題。因此,我在嘗試滾動到單元格之前將其更改爲第一響應者。

我試過用

[[self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

可惜的tableview不滾動到該小區,但所有其他細胞。當我爲此行添加一個斷點時,問題不會發生。它看起來像tableview滾動到單元格,但然後再次向下滾動。

這裏的cellForRowAtIndexPath的代碼:

UITableViewCell *cell; 
static NSString *AttributeCellIdentifier = @"AttributeCellIdentifier"; 
    cell = [tableView dequeueReusableCellWithIdentifier:AttributeCellIdentifier]; 
    if (cell == nil) { 
     [[NSBundle mainBundle] loadNibNamed:@"AttributeCell" owner:self options:nil]; 
     cell = attributeCell; 
     self.attributeCell = nil; 
     UITextField * textField = (UITextField *)[cell viewWithTag:1]; 
     [textField setKeyboardType:UIKeyboardTypeDecimalPad]; 
     [textField setInputAccessoryView:[self inputAccessoryView]]; 
    } 
UITextField * textField; 
textField = (UITextField *)[cell viewWithTag:1]; 
textField.placeholder = @"C(Probe)/mol/l"; 
return cell; 

下面是切換到以前的文本字段代碼:

UIView * currentResponder = [self.view findFirstResonder]; 

UITextField * newFocusTextField; 
UITableViewCell * cell = (UITableViewCell*)[[currentResponder superview] superview]; 
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell]; 

newFocusTextField = (UITextField*)[[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]] viewWithTag:1]; 
[currentResponder resignFirstResponder]; 
[newFocusTextField becomeFirstResponder]; 

UITableViewCell * newCell = (UITableViewCell*)[[newFocusTextField superview] superview]; 
NSIndexPath * newIndexPath = [self.tableView indexPathForCell:newCell]; 
[self.tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

希望這有助於。

+0

請發佈cellForRowAtIndexPath的代碼。你寫了這個方法的內容嗎?如果是這樣,爲什麼它返回零?如果不是,爲什麼不呢? – Rayfleck 2011-04-25 22:12:18

+0

我寫了這段代碼,我認爲它返回nil,因爲滾動不起作用時單元格不可見。從cellForRowAtIndexPath的文檔:表示表格單元格的對象,或者如果單元格不可見或indexPath超出範圍,則爲nil。 – 2011-04-25 22:35:25

+0

當您點擊工具欄顯示/編輯文本字段時,它是如何實現的?我想知道這裏是否有排序問題,即您可能需要滾動表格才能首先顯示單元格,然後使其成爲第一個響應者。 – Rayfleck 2011-04-25 23:38:57

回答

1

我試過幾個想法,現在一切正常。我刪除:

[currentResponder resignFirstResponder]; 

並移除該行的實現代碼如下滾動罰款後,我可以直接與newFocusTextField指針設置爲新的細胞,並使其firstResponder:

[newFocusTextField becomeFirstResponder]; 

我有一個nextTextField方法,它可以很好地工作

[currentResponder resignFirstResponder]; 

所以我不明白爲什麼會出現這個問題, r更好,然後首先退出currentResponder。

非常感謝您的幫助;)

2

你的文章和問題定義上的代碼不是百分之百清晰,但是在滾動方法的iOS 3.0工作中(我想具體是3.0,據我所知)存在一個錯誤/毛刺。我無法弄清楚它發生的原因,但它一直在崩潰,雖然iOS 4.x版本可以。

的修復是在滾動線之前加入一個

[table reloadData] 

。我知道這是沒有道理的,我知道這不是很好的做法,特別是如果單元渲染很昂貴,但它確實解決了這種情況的問題。我不知道你的問題是否來自同一個問題,但你可以試試...

+0

恐怕,但這並不能解決我的問題。我會編輯我的問題,更清楚地解釋我的問題。 – 2011-04-26 09:58:55