获取高度需要适合 UILabel 中的字符串



在我的Xamarin.iOS应用中,我有一个UILabel,它的宽度是300,包含一个很长的字符串。我需要调整UILabel框架的大小,使其高度适合整个字符串,同时保持宽度为 300。

UILabel myLabel;
myLabel.Text = "VERY LONG STRING!!!!!!!!111.....youGetThePoint"
myLabel.Font = UIFont.SystemFontOfSize(20, UIFontWeight.Bold);
// now I want to make myLabel's width 300 and the height to be the appropriate amount to see the whole text.
您可以使用

UILabel.sizeThatFits(CGSize size)

UILabel myLabel = ...;
myLabel.Text = "VERY LONG STRING!!!!!!!!111.....youGetThePoint"
myLabel.Font = UIFont.SystemFontOfSize(20, UIFontWeight.Bold);
myLabel.PreferredMaxLayoutWidth = 300
myLabel.Lines = 0
var maxSize = new CGSize((nfloat)300, nfloat.MaxValue);
var labelSize = myLabel.SizeThatFits(maxSize);

labelSize应该为您提供标签显示的非常长的文本的大小。

myLabel.Frame.Height = labelSize.Height; 

最新更新