像Mails应用程序一样绘制到UITableViewCell上

时间:2012-08-28 05:15:34

标签: iphone quartz-2d

所以我正在尝试做一些“简单”的事情,比如邮件应用程序,我的UITableVieCell子类告诉用户该对象中有多少项。所以一旦我抓住我的细胞,我就这样做了:

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];
    }

我最初尝试将此代码放在UITableViewCell的awakeFromNib方法中,但我的[map.locations count]总是小于0,即使在我的configureCell方法中它也不是。不知道为什么,在任何情况下,我在我的cellForRowAtIndexPath方法中调用configureCell,它执行上面的代码。它看起来非常可怕。

Screnshot: enter image description here

Apple如何通过邮件使他们变得如此美好?谢谢!

1 个答案:

答案 0 :(得分:0)

请参阅simple-table-badges链接,因为它也包含源代码。希望有帮助。

另请参阅链接中的@RedBlueThing ansswer