ios - 根据 UILabel 中的数字动态更改 UIView 宽度
<p><p>我有一个显示为条形的 <code>UIView</code>,其宽度应根据 <code>UILabel</code> 上显示的 <code>NSNumber</code> 值更改。</code> p>
<p>下图显示了 UI <a href="/image/KpjYX.png" rel="noreferrer noopener nofollow"><img src="/image/KpjYX.png" alt="enter image description here"/></a> </p>
<p><strong>例如:</strong> 如图所示,所有 3 个橙色条都有不同的值。我需要栏的宽度也应该根据值不同。值为 14 和 10 的条的宽度应小于值为 18 的条。</p>
<p>以下是我写的代码,但它不起作用。</p>
<pre><code>//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 = ;
//set the frame of the bar
CGRectrect = cell.barView.frame;
rect.size.width = s.size.width;
cell.barView.frame = rect;
</code></pre>
<p>有人可以帮忙吗:
如何根据值更改栏的宽度?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是你应该遵循的基本逻辑:</p>
<ul>
<li>获取柱数范围(例如 0-100)</li>
<li>获取宽度像素范围(例如 0-320)</li>
<li>为每 1 个您创建比例(例如 320/100)或 3.2 个像素的宽度
增加...</li>
</ul>
<p>所以根据上面的例子:</p>
<ul>
<li>如果条形为 100,则其宽度为 100 * 3.2 = 320 像素宽度</li>
<li>如果条形为 50,则其宽度为 50 * 3.2 = 160 像素宽度</li>
</ul>
<p>希望对您有所帮助。</p>
<pre><code>- (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 = ];
/*
Create the UIView here and set its witdh to the result of the CGFloat above (myViewWidth)
*/
</code></pre></p>
<p style="font-size: 20px;">关于ios - 根据 UILabel 中的数字动态更改 UIView 宽度,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/34187600/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/34187600/
</a>
</p>
页:
[1]