简体   繁体   中英

How to access properties on a custom UITableViewCell from a UiTableViewController?

I am trying to access a label property on a custom UiTableViewCell (subclassed UITableViewCell) from a UitableViewController class. For instance I have the heightForRowAtIndexPath method and I need to get access to the label.

Here is my code:

- (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath {

   // I need access to the custom UITableView Cell property here

}

Any tips? Also is it even possible to declare the outlet in the uiviewcontroller and link it to the label on the custom uitableviewcell?

Thanks

For accessing cell from heightForRowAtIndexPath: , check following:


If you need to access cell's label after it is initialized then you need to add tag to the label in the custom UITableViewCell class and you can access the label as following:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"cell"];
    UILabel *cellLabel = (UILabel *)[cell viewWithTag: 1];
}

The height calculation should be done with data from your data model, not the view. Remember, the cell was created with data from the data model.

You can't call [tv cellForRowAtIndexPath:indexPath] because this can cause infinite recursion between the tableView:cellForRowAtIndexPath: and this tableView:heightForRowAtIndexPath: method.

You can try directly calling your tableView:cellForRowAtIndexPath: method to get a cell but that may have undesired side effects.

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