Greg
Greg

Reputation: 34798

how to make a UIView added to UITableViewCell content view fit within its bounds?

how to make a UIView added to UITableViewCell content view fit within its bounds?

That is, I have created a single NIB file (with 3 labels on it), and want to use this for the display of each cell in a UITableView. I'm adding in the cellForRowAtIndexPath method the custom NIB based view to the cell's content view, however all I see as an end result is one (1) custom NIB based view (not multiple within a tableview as I expected).

How do I arrange so that each custom view fits neatly within each UITableViewCell? Also note the labels within the custom NIB view have word wrap.

Do I have to create a frame for the custom NIB view, but then in that case I'm not exactly sure how to set the co-ordinates. Would it be relative to the UITableViewCell? and if the custom view height can change due to it's UILabel word wrap, then I assume I separately have to manually calculate this height in the UITableView? (perhaps I should go to dynamic/custom view creation and drop the concept of using InterfaceBuilder/NIB)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    UIView *detailedView = [[[NSBundle mainBundle] loadNibNamed:@"DetailedAppointView" owner:self options:nil] objectAtIndex:0];
    [cell.contentView addSubview:detailedView];  // DOESN'T SEE TO WORK

    return cell;
}

Upvotes: 1

Views: 1551

Answers (1)

Cyprian
Cyprian

Reputation: 9453

This is how I do it if I need to implement a custom UITableViewCell.

I create a subclass of UITableViewCell for my custom cell ex. "MyCustomCell". Then I create a NIB file for it, and within this NIB file I insert UITableViewCell and change it's type to "MyCustomCell" and I give it an identifier with the same name as the class name. Then I insert all my subviews onto my cell. All in IB.

After I got my cell pimped out to my likning :-) I use it in the following way:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCustomCell";
    static NSString *CellNib = @"MyCustomCell";

    MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (MyCustomCell *)[nib objectAtIndex:0];
    }

    //Manipulate your custom cell here

    return cell;
}

Upvotes: 1

Related Questions