开发者

How to initialize UITableView? Both from XIB and programmatically?

I have a simple request that I have spent much time on (embarrassingly)..

I have sub-classed a UITableView to add some functionality. These new features require things like NSMutableSet which require allocation/initialization.

I have put my object's initialization routine in

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {

which I understood from the apple docs to correct - but this doesn't get called (determined by break-pointing on the code).

I am using IB, and have dragged a UITableView onto the view, and changed it's class to my new sub-class. There is no UITableViewController. I have also tried:

- (void)loadView {
- (id)init {
- (id)initWithFrame:(CGRect)frame {

with no success. I would like to have this class work both with IB, and programmatically in the future. Everything works apart from the location of th开发者_运维百科is initialization..


When objects load from a XIB file, they get -(id)initWithCoder:(NSCoder*)coder.

If you create objects from XIBs and programmatically, you'll need to implement both the designated initializer -initWithFrame:style: and -initWithCoder:, doing all your init stuff in each one.

Keeping those two in sync can be a pain, so most folks like to break the init stuff out into a private method, typically called -commonInit.

You can see an example of this in action in some of the Apple sample code: HeadsUpUI.

- (void)commonInit
{
    self.userInteractionEnabled = YES;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self commonInit];
    }
    return self;
}


One common mistake that people make when they're new to Cocoa or Cocoa Touch, is to subclass when they don't actually need to. I've seen many examples of custom windows, tableviews, scrollviews and imageviews that need never have been written.

What functionality are you adding to UITableView? Are you sure that what you want to do can't be accomplished through the delegate methods, or by using a custom cell class?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜