Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is diffrent between [cell addSubview:button] and [cell.contentview addsubview:button]

i have button in tableviewcell. what is diffrent between [cell addSubview:button] and [cell.contentview addsubview:button] ? because when i use [cell addSubview:button] in tableview , button function work fine but my interface in table view messed up and button go to left cell after i scroll in views and back to tableview. in other hand when i use [cell.contentview addsubview:button] button function not work and nothing save to myarray.

button code:

UIButton *button=(UIButton *) [cell viewWithTag:103];//fav
[button setImage:[UIImage imageNamed:@"unfav.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateSelected];
 button.frame = CGRectMake(0,0, 50, 50);

button.tag = indexPath.row;
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button]; // add the button to the cell
[cell bringSubviewToFront:button];
like image 203
Mehdi Negahban Avatar asked Sep 12 '25 20:09

Mehdi Negahban


1 Answers

The contentView is the default view for the cell in which all the subviews are added.The cell.view is the main view in which contentView is itself added and cell.contentView covers the whole area of the cell.view. But in your case when you added the button to cell.view.

From apple docs about ContentView,

The content view of a UITableViewCell object is the default SuperView for content displayed by the cell. If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewCell_Class/#//apple_ref/occ/instp/UITableViewCell/contentView

like image 114
Muhammad Zohaib Ehsan Avatar answered Sep 15 '25 09:09

Muhammad Zohaib Ehsan