简体   繁体   中英

UITableViewCell Subclass - Adding a subview on IBAction

I'm trying to add a subview to the UIViewController 's view when the UITableViewCell 's button inside the view is triggered. The problem im facing is to call the parentview from the table view cell's subclass.

You can lookup parent tableView in view hierarchy:

-(UITableView*) parentTableView
{
    UIView* v = [self superview];
    while (v && ![v isKindOfClass:[UITableView class]]) {
        v = [v superview];
    }
    return v;
}

When you create the tableviewcell subclass, pass it a pointer to the instance of the parentview by making your own init method. Then save that pointer in your subclass as an instance variable. That way you can do what ever you want to the parent when something happens in the subclass. Let me know if you need more help.

I'd suggest to set the UIViewController the delegate for the UITableViewCells . You have to create a protocol and make the UIViewController implement it. Furthermore you need to subclass UITableViewCell in order to add the delegate property.

#import <Foundation/Foundation.h>

@protocol YourTableViewCellDelegate

  - (void)didTouchButton:(UIButton *)theButton;

@end

In the action method for the UIButton check for the existence of the delegate:

if (self.delegate != nil && [self.delegate respondsToSelector:@selector(didTouchButton:)]) {
    [self.delegate performSelector:@selector(didTouchButton:) withObject:_theButton];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM