UIAlertController 自定义字体不起作用。
下面的代码是一个函数ShowActionSheetAsync
, 显示 ActionSheet
.
此时,我想更改ActionSheet
的字体.我尝试了几种方法,但效果不佳。有好的解决办法吗?
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;
}
第一次尝试 以下代码无法正常工作。
当我将代码放在
[Block 1]
上时或[Block 2]
- 根本行不通
当我将代码放在
[Block 3]
上时- 仅在首秀时适用
ActionSheet
.从第二次开始,就不行了
- 仅在首秀时适用
UILabel.AppearanceWhenContainedIn(typeof(UIActionSheet)).Font
= UIFont.FromName(StyleResources.MediumFontName, 20);
第二次尝试 以下代码也无法正常工作。
当我将代码放在
[Block 2]
上时- 短时间显示默认字体后,显示自定义字体
当我将代码放在
[Block 3]
上时- 它只适用于
cancel
按钮
- 它只适用于
FindDescendantViews<UILabel>()
是 UIView
的扩展方法并返回适当类型的所有 subview 。
var labels = alert.View.FindDescendantViews<UILabel>();
foreach (var label in labels)
{
label.Font = UIFont.FromName(StyleResources.MediumFontName, 20);
}
最佳答案
UIAlertController
UILabels
可以使用 attributedTitle
键通过 KVC 设置字体和颜色。在 [Block 3]
func changeAlert(alert: UIAlertController, backgroundColor: UIColor, textColor: UIColor, buttonColor: UIColor?) {
let view = alert.view.firstSubview().firstSubview()
view.backgroundColor = backgroundColor
view.layer.cornerRadius = 10.0
// set color to UILabel font
setSubviewLabelsToTextColor(textColor, view: view)
// set font to alert via KVC, otherwise it'll get overwritten
let titleAttributed = NSMutableAttributedString(
string: alert.title!,
attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(17)])
alert.setValue(titleAttributed, forKey: "attributedTitle")
let messageAttributed = NSMutableAttributedString(
string: alert.message!,
attributes: [NSFontAttributeName:UIFont.systemFontOfSize(13)])
alert.setValue(messageAttributed, forKey: "attributedMessage")
// set the buttons to non-blue, if we have buttons
if let buttonColor = buttonColor {
alert.view.tintColor = buttonColor
}
}
func setSubviewLabelsToTextColor(textColor: UIColor, view:UIView) {
for subview in view.subviews {
if let label = subview as? UILabel {
label.textColor = textColor
} else {
setSubviewLabelsToTextColor(textColor, view: subview)
}
}
}
关于c# - UIAlertController 自定义字体在 iOS 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37406030/