集合视图单元的动态宽度 - Xamarin iOS

时间:2017-09-25 12:47:17

标签: ios xamarin xamarin.ios

我想让Cell宽度与其内容相关。我试过计算标签宽度,然后将其分配给单元格框架,但无法实现这一点,因为标签没有返回它的实际宽度。

public void UpdateCell(string text)
{
    label.Text =  text;
    this.ContentView.Frame = new CoreGraphics.CGRect(0, 0, label.Frame.Width, this.ContentView.Frame.Height);
}

1 个答案:

答案 0 :(得分:0)

您可以使用NSString的GetSizeUsingAttributes来计算字符串的CGRect,然后您可以使用CGRect来检索宽度:

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);
}