我想为 iOS 13+ 自定义上下文菜单上的操作按钮
菜单是这样的:
我想我可以像 UIAlertController 操作一样设置自定义字体,如下所示:
let action = UIAction(title: "asdasd") { _ in}
let attributeString = NSMutableAttributedString(string: action.title)
attributeString.addAttributes([NSAttributedString.Key.font : font], range: NSMakeRange(0, action.title.count))
action.setValue(attributeString, forKey: "attributedMessage")
但它不是那样工作的,那是怎么样的呢?
您不能强制它使用特定的字体和/或文本大小。它实际上支持动态文本。因此它的大小将取决于用户设备设置。
Settings > Display & Brightness > Text Size
和 Settings > Accessibility > Larger Text
(iOS 14)。因此,您无法使用自定义字体,因为上下文菜单支持动态文本。动态文本使用的字体取决于系统,因此从 iOS 9 开始,Apple 使用 San Francisco 字体。有关 iOS 中动态类型的更多信息,您可以阅读这篇文章。
在 iOS 17 中,如果将 _attributedTitle 设置为键并使用 UIFont PreferredFontForTextStyle 作为字体大小,则可以使用
CGFloat pointSize = [UIFont PreferredFontForTextStyle:UIFontTextStyleSubheadline].pointSize; UIFont *font = [UIFont fontWithName:@"字体名称" size:pointSize];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[action title]];
[string addAttributes:@{NSFontAttributeName:font} range:NSMakeRange(0, [[action title] length])];
[action setValue:string forKey:@"_attributedTitle"];