根据UILabel中的数字动态更改UIView宽度

时间:2015-12-09 19:41:46

标签: ios objective-c uiview

我的UIView显示为条形图,其宽度应根据NSNumber上显示的UILabel值进行更改。

下面的图片显示了ui enter image description here

例如:如图所示,所有3个橙色条都有不同的值。我需要条的宽度也应该根据值不同。值为14和10的条的宽度应小于值为18的条。

以下是我写的代码,但它不起作用。

//Get the value as string
        NSString *countString = cell.numberOfTuneIn.text;
        //MAximum size of the bar
        CGSize maxSize = CGSizeMake(cell.numberOfTuneIn.bounds.size.width, CGFLOAT_MAX);

        CGRect s = [countString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:cell.numberOfTuneIn.font} context:nil];

        //set the frame of the bar
        CGRect  rect = cell.barView.frame;
        rect.size.width = s.size.width;
        cell.barView.frame = rect;

有人可以帮忙: 如何根据值更改条的宽度?

1 个答案:

答案 0 :(得分:1)

这是你应该遵循的基本逻辑:

  • 获取条形码范围(例如0-100)
  • 获取宽度像素范围(例如0-320)
  • 为每个1创建比例(例如320/100)或3.2像素宽度 增量...

所以根据上面的例子:

  • 如果条形为100,则宽度为100 * 3.2 = 320像素宽度
  • 如果条形为50,则其宽度为50 * 3.2 = 160像素宽

希望它有所帮助。

- (CGFloat)getViewlWidth:(float)labelValue {

    // Setup view bar settings, you can take those settings outside of this method if needed
    int maxLabelValue = 100;
    int viewMaxWidth = 320; // You can make it dynamic according to screen width
    float widthPixelRatio = viewMaxWidth / maxLabelValue;

    // Calculate width 
    CGFloat pixelsResult = labelValue * widthPixelRatio;

    // Return value
    return pixelsResult;
}

// Lets assume that here you get the label value from the server and you called it labelValue
NSString * labelValue = // Value from server

/*
Create UILabel here, showing the value from server
*/

// Get the width of the UIView to be
CGFloat myViewWidth = [self getViewlWidth:[labelValue floatValue]];

/*
Create the UIView here and set its witdh to the result of the CGFloat above (myViewWidth)
*/
相关问题