UIAlertController custom font doesn't work.
The following code is a function ShowActionSheetAsync
, show ActionSheet
.
At this point, I want to change the font of ActionSheet
. I have tried several ways, but it didn't work well. Is there good solution?
public Task<bool> ShowActionSheetAsync()
{
var source = new TaskCompletionSource<bool>();
var alert = new UIAlertController
{
Title = "title"
};
alert.AddAction(UIAlertAction.Create(
"button1",
UIAlertActionStyle.Default,
_ => source.SetResult(true)));
alert.AddAction(UIAlertAction.Create(
"cancel",
UIAlertActionStyle.Cancel,
_ => source.SetResult(false)));
// [Block 1]
var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
ViewController.PresentViewController(alert, true, delegate
{
// [Block 2]
});
// [Block 3]
return source.Task;
}
First attempt The following code does not work properly.
When I put the code on
[Block 1]
or[Block 2]
- It does not work at all
When I put the code on
[Block 3]
- Applies only when the first show
ActionSheet
. From the second times, it does not work
- Applies only when the first show
UILabel.AppearanceWhenContainedIn(typeof(UIActionSheet)).Font
= UIFont.FromName(StyleResources.MediumFontName, 20);
The second attempt The following code also does not work properly.
When I put the code on
[Block 2]
- After showing the default font for a short time, showing the custom font
When I put the code on
[Block 3]
- it work on only
cancel
button
- it work on only
FindDescendantViews<UILabel>()
is a extension method for UIView
and returns all child view of appropriate type.
var labels = alert.View.FindDescendantViews<UILabel>();
foreach (var label in labels)
{
label.Font = UIFont.FromName(StyleResources.MediumFontName, 20);
}
I have the solution here. I created a custom AlertThemeConfigurator that recursively runs through all the subviews looking for UILabels, then sets the themed attributedText on them for the title, message, and different types of actions. Feel free to style the attributed strings appropriately.
To present it call
It's not allowed to either subclass or change default things of an UIAlertController. You need to make a custom view for it.
UIAlertController
UILabels
font and color can be set via KVC using theattributedTitle
key. Use this in[Block 3]