开发者

Change Height of UITableViewCell from within the UITableViewCell inherited class when UITextField receive focus

I have a inherited UITableViewCell class from which I create a custom cell containing a UITe开发者_StackOverflow中文版xtField.

The UITextField is 25 pixel height by default.

The behavior I want is that when the user clicks in the textField, the UITextField should change to 100 pixel height and the cell should grow accordingly.

I can detect when the UITextField receive focus thanks to notifications and observers but I wonder how to programmatically make that tableView:HeightForCellAtindexPath: be called.


Like Endemic says, tableView:heightForCellAtIndexPath: is the method you need to implement. According to Apple, the most efficient way to trigger a resize is an empty beginUpdates / endUpdates block, like this.

[tableView beginUpdates];
[tableView endUpdates];

It saves you the overhead of reloading the cell contents and, I believe, gives you a nice animation you wouldn't otherwise get from reloadData.


You must have a link between the cell and the table view controller. Since you are already creating your custom cell in your controller the easiest way would be to use the delegate pattern.

@class CustomTableViewCell;

@protocol CustomTableViewCellDelegate 
- (void)customTableViewCellDidEnterTextMode:(CustomTableViewCell *)cell;
@end

@protocol (nonatomic, assign) id<CustomTableViewCellDelegate> delegate;

and just call the delegate method where you are detecting when the text field gets focus

[self.delegate customTableViewCellDidEnterTextMode:self];

and in the controller

- (void)customTableViewCellDidEnterTextMode:(CustomTableViewCell *)cell {
  self.editingIndexPath = [self.tableView indexPathForCell:cell];
  // from Jablair's answer
  [tableView beginUpdates];
  [tableView endUpdates];
}

And then in tableView:heightForCellAtIndexPath: just return your special height for self.editingIndexPath.

You would probably have to include another delegate method to know when focus is leaving the text field as well.

Another approach would be to use notifications but that will just complicate your code and if there is only one receiver of the message a delegate is the preferred way. A third approach would be to set the delegate of the text field to your controller instead of to your cell.

The bottom line, you need to provide the link between the cell and table view your self and I believe using a delegate pattern is the best approach.


The tableView:heightForCellAtIndexPath: method is called whenever the table view loads data, so simply calling reloadData (or one of the other, more selective reload methods) on the table view should work fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜