Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add uiviewcontroller's view as content view to uitableviewcell?

I want to add a uiviewcontroller's view which has a button and few labels as a content view of a uitableviewcell.

Though i am able to add but the button action causes a crash.

MyViewController *controller = [[MyViewController alloc] initwithnibname:@"MyView" bundle:nil];
[cell.contentview addsubview:controller.view];
[controller release]; // if i comment out this part the button action is received by my view controller.

However there are memory leaks when its removed from view. The dealloc of myviewcontroller is not called.

What is the correct way to do this?

  1. Add a view to a uitableview cell which has a button and is handled by the viewcontroller

  2. How to assure memory is released when the view goes out of scope?

TIA, Praveen

like image 777
Praveen S Avatar asked Apr 08 '11 14:04

Praveen S


1 Answers

I think the problem is, that you are releasing the controller and just using the subview which is retained by its superview. The action pattern needs a target which I assume is the released controller. And why should you release your viewController if you only need the view of it? Retain it and keep a reference through a property to it.

My way of adding subviews to a tableview cell would be in a subclass of UITableViewCell. Let's assume you are having a subclass of UITableViewCell, say ButtonTableViewCell. The init of the of cell creates and adds a UIButton to your cell and puts it nicely in its contentView. Decalre a property which references to the button. Like UIButton *myButton. What should be done in the cellForRowAtIndexPath is something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyButtonCell"];           
    if (cell == nil) {
        cell = [[ButtonTableViewCell alloc] initWithReuseIdentifier:@"MyButtonCell"];
    }
    [cell.myButton addTarget:self action:@selector(onDoSomething) forControlEvents:UIControlEventTouchUpInside];

    // Do more cell configuration...
    return cell;
}

I've made up the initializer initWithReuseIdentifier which can be easily implemented.

You assure release of memory with the viewDidUnload method of the UIViewController and the dealloc method.

like image 172
Nick Weaver Avatar answered Nov 15 '22 20:11

Nick Weaver