How to add UIView to custom UITableViewCell in drawRect method

319 Views Asked by At

In my project need to add uiview in UITableViewCell. I can add UIView using following code in UITableViewCell class.

    -(void)drawRect{
       [cell.contentView addSubview:myView];
    } 

Is this a efficient way to show when large amount of table cell are displaying. Is there other way to add UIView using method like.

    drawInRect
2

There are 2 best solutions below

0
On

You will want to add the subView in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath which is part of UITableViewDataSource protocol.

0
On

Don't use drawRect method that way. That method is using for drawing some parts of the ui-element and may call several times per a sec. You should add a subview in cellForRowAtIndexPath method (UITableViewDataSource protocol) or in - (void)awakeFromNib. Don't forget to remove that subview in - (void)prepareForReuse method of your UITableViewCell subclass.