Bouncing custom table cell all the way to the top
I am struggling with a custom table cell which I need to move all the way to the top of the screen when its text field becomes first responder (not just somewhere above the keyboard where it automatically goes). This because I need some room for a suggestion drop down box in between the text field and the开发者_运维问答 keyboard when the user starts typing.
I am not able to figure out how to attack this problem correctly :( Input will be greatly appreciated...
Thanks a lot,
StineYou should move the whole table, not just the cell. You can get the rect for the cell and move the table accordingly.
UITableView has methods to do this: moveRowAtIndexPath. There are lots of posts on SO that already cover this. Try here.
Edit: You can also use the table scrolling methods to scroll the table to a row below the one you want.
– scrollToRowAtIndexPath:atScrollPosition:animated:
– scrollToNearestSelectedRowAtScrollPosition:animated:
You may be able to do this by scrolling the table such that the cell containing the editing text field appears at the top of the visible table view - take a look at scrollToRowAtIndexPath:atScrollPosition:animated:
in UITableView
. Call it with UITableViewScrollPositionTop
as the 2nd argument to achieve that effect. See also the UITableView documentation. For example:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
// quick and dirty way to obtain a reference to the cell containing the textField
UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[self.tableView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
}
Then, you could add the 'suggestion drop down box' as a subview of your top-level view, making it appear above the tableView and positioning it accordingly.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// assuming |suggestionBox| is a property owned by your controller
if (![suggestionBox superview]) {
// Set-up the suggestion box view here; have your controller retain it.
// self.suggestionBox = [[UIView alloc] initWithFrame: ...];
// ...
// [self.view addSubview:suggestionBox];
}
// Update the content of the suggestion box using the replacement string, e.g.:
// NSArray *suggestions = [self suggestionsWithString:string];
// [self.suggestionBox setSuggestions:suggestions];
return YES;
}
I wrote the code above in comments because it requires a few elements to be set-up, and that depends entirely on you. You would also have to make sure that you implement the appropriate logic to hide the suggestions drop down when it makes sense.
I hope this points you toward a working solution...
精彩评论