Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

badge view in UITableViewCell

i Want to create a badgeView which is inserted in the cells accesoryView. I know this have been asked quite a lot in the past, but those github subclasses, seem to be outdated and cant be ported into an swift project. What is the easiest way to do it in IOS in a swift project?

Something like this:

enter image description here

like image 757
gamerChristian Avatar asked Sep 30 '14 20:09

gamerChristian


1 Answers

The following code has been testing in iOS7 and iOS8 and works as follows:

  1. If count > zero, it will display the count in white text with a red badge around it.
  2. If count = zero, it will display a simple disclosure indicator.



enter image description here


    - (void)updateTableViewCell:(UITableViewCell *)cell forCount:(NSUInteger)count
    {
        // Count > 0, show count
        if (count > 0) {

            // Create label
            CGFloat fontSize = 14;
            UILabel *label = [[UILabel alloc] init];
            label.font = [UIFont systemFontOfSize:fontSize];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.backgroundColor = [UIColor redColor];

            // Add count to label and size to fit
            label.text = [NSString stringWithFormat:@"%@", @(count)];
            [label sizeToFit];

            // Adjust frame to be square for single digits or elliptical for numbers > 9
            CGRect frame = label.frame;
            frame.size.height += (int)(0.4*fontSize);
            frame.size.width = (count <= 9) ? frame.size.height : frame.size.width + (int)fontSize;
            label.frame = frame;

            // Set radius and clip to bounds
            label.layer.cornerRadius = frame.size.height/2.0;
            label.clipsToBounds = true;

            // Show label in accessory view and remove disclosure
            cell.accessoryView = label;
            cell.accessoryType = UITableViewCellAccessoryNone;
        }

        // Count = 0, show disclosure
        else {
            cell.accessoryView = nil;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
like image 94
nurider Avatar answered Oct 02 '22 12:10

nurider