我的UIView
显示为条形图,其宽度应根据NSNumber
上显示的UILabel
值进行更改。
例如:如图所示,所有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;
有人可以帮忙: 如何根据值更改条的宽度?
答案 0 :(得分:1)
这是你应该遵循的基本逻辑:
所以根据上面的例子:
希望它有所帮助。
- (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)
*/