菜鸟教程小白 发表于 2022-12-11 18:46:17

ios - Collection View 单元格的动态宽度 - Xamarin iOS


                                            <p><p>我想让单元格宽度相对于其内容动态。我尝试通过计算标签宽度然后将其分配给单元格框架但无法实现这一点,因为标签没有返回它的实际宽度。</p>

<pre><code>public void UpdateCell(string text)
{
    label.Text =text;
    this.ContentView.Frame = new CoreGraphics.CGRect(0, 0, label.Frame.Width, this.ContentView.Frame.Height);
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以使用 NSString 的 <code>GetSizeUsingAttributes</code> 来计算字符串的 <code>CGRect</code>,然后您可以使用该 <code>CGRect</code> 来检索宽度:</p>

<pre><code>using (var labelString = new NSString(label.Text))
{
    var size = labelString.GetSizeUsingAttributes(new UIStringAttributes() { Font = label.Font });
    ContentView.Frame = new CGRect(0, 0, size.Width, ContentView.Frame.Height);
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios -Collection View 单元格的动态宽度 - Xamarin iOS,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/46405637/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/46405637/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Collection View 单元格的动态宽度 - Xamarin iOS