我的应用程序支持 iOS 13 深色模式,并为用户提供匹配系统外观或强制应用程序始终使用深色模式或浅色模式的选项,无论系统设置如何。
该应用程序还允许在用户按下
UILabel
时显示上下文菜单。但是,当使用 UIContextMenuInteractionDelegate
方法呈现上下文菜单时,我找不到任何方法来覆盖菜单的深色/浅色外观,也找不到在上下文菜单出现和消失时动画显示的 UITargetedPreview
视图的外观。
例如,如果 iOS 外观设置为浅色模式,并且用户在应用程序中选择了强制深色模式的选项,则上下文菜单会显示为浅色。我想覆盖该行为,使它们看起来很暗 - 有什么办法可以实现这一目标吗?似乎没有
overrideUserInterfaceStyle
属性与我能找到的上下文菜单相关联。
我使用的代码在下面供参考。
// Setup code
if #available(iOS 13.0, *) {
self.textLabel.addInteraction(UIContextMenuInteraction(delegate: self))
}
// UIContextMenuInteractionDelegate
@available(iOS 13.0, *)
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
let text = self.text
return UIContextMenuConfiguration(identifier: nil, previewProvider: { return TextViewController(text: text) }) { [weak self] _ in
return self?.contextMenu(for: text)
}
}
@available(iOS 13.0, *)
private func contextMenu(for text: String) -> UIMenu {
let copy = UIAction(title: "Copy", image: UIImage(systemName: "doc.on.doc")) { _ in
// Perform 'text' copy
}
let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { _ in
// Present system share sheet
}
return UIMenu(title: "", children: [copy, share])
}
我使用以下方法强制显示上下文菜单的视图控制器的外观:
overrideUserInterfaceStyle = .dark // or .light
所以,我面临的问题不是
UIViewController
中的 UI 元素,只是它显示的上下文菜单。
在 iOS 13 及更高版本的
AppDelegate
或 SceneDelegate
中添加以下行。
self.window?.overrideUserInterfaceStyle = .light / .dark
UIViewController
:为
ViewDidLoad
添加以下赞:
self.overrideUserInterfaceStyle = .light / .dark
UIView
:view.overrideUserInterfaceStyle = .light / .dark
2022 年,我无法通过委托方法覆盖长按集合视图单元格时填充的 UIMenu 的样式
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration?
我的应用程序的上下文:
.overrideUserInterfaceStyle = .light
.light(有时也在导航栏上设置)试图设置与集合的子视图或其他视图相关的所有内容,只是具有
.overrideUserInterfaceStyle
属性的所有内容,什么都没有。如果用户的 iOS 处于深色模式,则长按收藏视图会显示深色UIMenu
。如果用户有灯光模式,则显示灯光UIMenu
。
对我有用:
if let keyWindow = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap { $0.windows }.first { $0.isKeyWindow } {
keyWindow.overrideUserInterfaceStyle = darkThemeIsNeeded ? .dark : .light
}