首页 文章

根据Xamarin.iOS中的Frame调整UILabel的字体大小

提问于
浏览
1

我想动态调整UILabel的文本大小 . UILabel的框架将动态更改 . 每当更改UILabel的Frame时,字体大小都应该适合框架 .

我试过下面的代码,但没有效果 .

label.AdjustsFontSizeToFitWidth = true

最后我找到了解决方案

这是我的计算

void ResizeLabelFontSize(CGRect frame,UILabel label)
    {
        int fontSize = 3;
        UIFont font = UIFont.SystemFontOfSize(fontSize);
        CGSize size = label.Text.StringSize(font);
        while (frame.Width > size.Width)
        {
            fontSize++;
            font = UIFont.SystemFontOfSize(fontSize);
            size = label.Text.StringSize(font);
        }
        label.Font = UIFont.SystemFontOfSize(fontSize);
    }

1 回答

  • 0

    你可以看 AdjustsFontSizeToFitWidth 定义here

    正如文档所述,在roder中的大小将是 reduced 以适合标签's bounding rectangle, so the font will not get larger dynamically with label'的框架,但是您可以在开头设置非常大的字体以达到您的要求,请参阅我的测试结果 .

    代码段:

    UILabel label;
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
    
        label = new UILabel(frame: new CGRect(0, 100, 100, 100));
        label.BackgroundColor = UIColor.Red;
        label.TextColor = UIColor.White;
        label.Font = UIFont.SystemFontOfSize(1000);
        label.AdjustsFontSizeToFitWidth = true;
        label.LineBreakMode = UILineBreakMode.Clip;
        label.BaselineAdjustment = UIBaselineAdjustment.AlignCenters;
        label.Text = "label";
        View.AddSubview(label);
    }
    
    partial void ButtonIncrease(UIButton sender)
    {
        CGRect rect = label.Frame;
        rect.Width = 300;
        rect.Height = 300;
        label.Frame = rect;
    }
    
    partial void ButtonDecrease(UIButton sender)
    {
        CGRect rect = label.Frame;
        rect.Width = 100;
        rect.Height = 100;
        label.Frame = rect;
    }
    

    enter image description here

相关问题