Search code examples
iphonequartz-2d

drawing onto UITableViewCell like Mails app


So I'm trying to do something "simple" like the mails app where my UITableVieCell subclass tells the user how many items belong in that object. So once I grab my cell, I do this:

if ([map.locations count] > 0) {
        UIView *locationsView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LOCATIONS_VIEW_LENGTH, LOCATIONS_VIEW_LENGTH)]; // LOCATIONS_VIEW_LENGTH is 20.0
        locationsView.frame = CGRectMake((cell.contentView.frame.size.width - 45), (cell.contentView.frame.size.height - locationsView.frame.size.height) / 2, LOCATIONS_VIEW_LENGTH, LOCATIONS_VIEW_LENGTH);
        locationsView.layer.backgroundColor = [UIColor grayColor].CGColor;
        [locationsView.layer setCornerRadius:3];

        UIFont *arialFont = [UIFont systemFontOfSize:12.0];
        NSString *locationsText = [NSString stringWithFormat:@"%i", [map.locations count]];
        CGSize locationsLabelSize = [locationsText sizeWithFont:arialFont constrainedToSize:locationsView.frame.size lineBreakMode:UILineBreakModeTailTruncation];
        UILabel *numLocationsLabel = [[UILabel alloc] initWithFrame:CGRectMake((locationsView.frame.size.width - locationsLabelSize.width) / 2, (locationsView.frame.size.height - locationsLabelSize.height) / 2, locationsLabelSize.width, locationsLabelSize.height)];
        numLocationsLabel.text = locationsText;
        numLocationsLabel.textColor = [UIColor whiteColor];
        numLocationsLabel.font = arialFont;
        numLocationsLabel.backgroundColor = [UIColor clearColor];
        [locationsView addSubview:numLocationsLabel];

        [cell.contentView addSubview:locationsView];
    }

I originally tried putting this code in an awakeFromNib method of the UITableViewCell, but my [map.locations count] was always less than 0 even though in my configureCell method it was not. Not sure why that is, in any case, I call configureCell in my cellForRowAtIndexPath method and it does the above code. It looks pretty horrible.

Screnshot: enter image description here

What does Apple do to make theirs so nice in mail? Thanks!


Solution

  • Refer simple-table-badges link as it contains sourcode also.Hope helpful.

    Also refer @RedBlueThing ansswer in link