0

需要一些小费。我在表格视图中有 2 个单元格。

第一个有一个 label.text 值,假设为 2。第二个的值为 1。

总数为 3 (100%)

我想用代表百分比值的颜色直观地显示单元格。

所以第一个单元格应该是 ca 67%,第二个单元格应该是 33%。

但是我怎样才能用颜色填充 67% 和 33% 的单元格呢?如果只有一个单元格有值,那么整个单元格将被颜色填充。另一个应该是空白的。

我希望它们看起来像条形图。

像这样:

在此处输入图像描述

4

3 回答 3

2

您可以做的是添加一个 UIView 作为带有颜色的背景。但是将视图的高度更改为单元格高度的百分比

CGRect frame = cell.frame;
frame.size.height = frame.size.height*0.66; //The 0.66 is the percentage as a decimal
frame.origin.y = cell.frame.size.height - frame.size.height; //adjust where it should start
UIView *bg = [[UIView alloc] initWithFrame:frame];
bg.backgroundColor = [UIColor redColor];
cell.backgroundView = bg;

这会将 UIView 添加到 cell.backgroundView ,其颜色开始稍微向下以表示您的填充百分比。

希望这可以帮助

于 2013-10-18T16:25:40.697 回答
1

我假设你可以通过数学计算出你想要使用的颜色的百分比。然后就很简单了:

UIView *bg = [[UIView alloc] initWithFrame:frame];
bg.backgroundColor = [UIColor colorWithHue:hue 
                                saturation:percent
                                brightness:brightness
                                     alpha:1.0];
cell.backgroundView = bg;

根据您的具体目标,您可能希望使用饱和度和亮度的组合,但使用恒定的色调和 alpha。

编辑:

如果您希望背景是条形图,就像您在链接中显示的那样,您需要制作一个稍微复杂的背景视图。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const CellIdentifier = @"MyCellIdentifier";
    static const NSInteger BarTag = 0xBEEF;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
                                                            forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier];
        UIView *background = [[UIView alloc] initWithFrame:cell.bounds];
        background.autoresizeMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        UIView *bar = [[UIView alloc] initWithFrame:cell.bounds];
        bar.autoresizeMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin;
        bar.tag = BarTag;
        bar.backgroundColor = [UIColor redColor];
        [background addSubView:bar];
        cell.backgroundView = background;
    }

    CGFloat percent = .5; // Calculate this somehow
    UIView *backgroundBar = [cell.backgroundView viewWithTag:BarTag];
    CGFrame frame = backgroundBar.frame;
    frame.size.width = CGRectGetWidth(tableView.frame) * percent;
    backgroundBar.frame = frame;

    return cell;
}
于 2013-10-19T04:25:52.733 回答
0

可悲的是 mashdup 的答案不正确。它为整个单元格着色(我使用的是 Swift)。

编辑:

var frame: CGRect = cell.frame
        frame.size.width = frame.size.width*0.66 //The 0.66 is the percentage as a decimal
        frame.origin.y = cell.frame.size.height - frame.size.height //adjust where it should start
        var bg: UIView = UIView(frame: frame)
        bg.backgroundColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.5)
        cell.addSubview(bg)

用 Swift 回答。

于 2015-03-08T13:50:44.423 回答