在所有UI按钮上设置自定义字体

本文关键字:设置 自定义 字体 按钮 UI | 更新日期: 2023-09-27 18:21:20

我想为我在Xamarin中创建的iOS应用程序中的所有按钮应用自定义字体。我已经用以前的代码实现了标签上的自定义字体:

//Labels
UILabel.Appearance.Font = UIFont.FromName("Lato-Light",16f);

这由于某种原因影响了一些但不是所有按钮。然后我试着瞄准按钮上的标签,就像这样:

var buttonAppearance = UILabel.AppearanceWhenContainedIn(typeof (UIButton));
buttonAppearance.Font = UIFont.FromName("Lato-Light", 16f);

这毫无作用。我应该以按钮标题为目标吗?我知道这里有很多关于如何在Xcode中设置这个的问题,但我正在Xamarin.iOS中使用C#。谢谢!

在所有UI按钮上设置自定义字体

因此,由于没有UIButton.Appearance.Font,您可以使用我通常使用的C#解决方法。

制作这样的扩展方法(在静态类中):

public static void ApplyTheme(this UIButton button)
{
    //Set the font on the button or whatever
}

然后从你应用程序中每个UIButton上的代码调用这个:

//In ViewDidLoad, AwakeFromNib, etc.
myButton.ApplyTheme();

这将为您提供所有按钮的样式,您可以在应用程序更改时修改这些按钮。

您可以使用它为按钮文本设置自定义字体。

UIButton.TitleLabel.Font=UIFont.FromName("Lato Light",16f);