OGeek|极客世界-中国程序员成长平台

标题: ios - 根据 UILabel 中的数字动态更改 UIView 宽度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:26
标题: ios - 根据 UILabel 中的数字动态更改 UIView 宽度

我有一个显示为条形的 UIView,其宽度应根据 UILabel 上显示的 NSNumber 值更改。 p>

下图显示了 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;

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



Best Answer-推荐答案


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

所以根据上面的例子:

希望对您有所帮助。

- (CGFloat)getViewlWidthfloat)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)
*/

关于ios - 根据 UILabel 中的数字动态更改 UIView 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34187600/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4