Search code examples
iphoneobjective-ciosuitableviewsubclassing

Subclassed UITableView


I want a subclass of UITableView that paints custom Section headers. I tryed as follows:

#import <UIKit/UIKit.h>
@interface MyTableView : UITableView
@end
@implementation MyTableView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  //my drawing code goes here
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
  //returns the height
}
@end

However when I use this class it draws the normal headers. What am I doing wrong?

When I Set those functions directly into a controller (without subclassing) it works fine.

UPDATE: I already have many classes that use UITableView, I want to subclass it because it may be faster to just change the class that writing the needed classes. How can I change the titles by just changing the class, is it possible?


Solution

  • This is happening because you inherited the UITableView class and this methods are not from UITableView, they are from the UITableViewDelegate.

    It works on your controller because either you have set the delegate property of your UITableView pointing to your controller, or you are using a UITableViewController, which has the tableview delegate set automatically. (Actually, in your case, using a UITableViewController is worse because it already implements UITableView instead of your custom class).

    EDIT: Unfortunately, due to the delegation pattern used in UITableView class to change its section header views, it is not straightforward to implement this kind of action

    One way of doing that is providing these "helper" methods in your class, and then implement the delegate on each of your controllers to call these methods properly when the delegate method is fired.

    If this approach is acceptable you should even consider using a category with these methods instead of subclassing you UITableView, which would make the code much cleaner.

    Obviously you could set the UITableView delegate to be your custom class and then create another delegate for the calls you still want to be fired to the controller, such as cellForRowAtIndexPath, and then call this new delegate methods as soon as the tableview fires the methods, but this is by far the worst possible solution