首页 > 解决方案 > 更改 ContextMenu iOS 外观(背景和突出显示颜色)

问题描述

我正在开发我的 React-Native 应用程序,我使用的是在 Native Context Menu 组件之上编写的RN ContextMenu iOS 库,除了背景和突出显示颜色行为外,一切正常。

看起来默认高亮和背景颜色遵循 iOS 主题,所以它可以是黑色或白色。虽然这种行为不适合我的应用程序的颜色,我想改变它,但我是 Objective-c 的新手,所以我不明白我应该改变什么部分。

为了清楚起见,我做了一个小演示,显示丑陋的白色高光和背景颜色:https ://www.youtube.com/watch?v=AASqQXXtRwE&feature=youtu.be

我相信我应该更改此文件中的某些内容-> https://github.com/mpiannucci/react-native-context-menu-view/blob/master/ios/ContextMenuView.m

理想情况下,我想让bg颜色透明,你们能帮帮我吗?

标签: iosobjective-creact-native

解决方案


您需要使用contextMenuInteraction:previewForHighlightingMenuWithConfiguration:方法。它允许返回 ContextMenu 的自定义预览,包括设置UIPreviewParameters,其中包括backgroundColor,应设置为透明。


主要挑战是它需要一个视图来显示,但在react-native-context-menu-view我们只能UIContextMenuInteraction在交互时访问。

为了解决这个问题,我们可以创建一个interaction -> view地图:

NSMapTable *interactionToViewMap = [NSMapTable weakToWeakObjectsMapTable];

然后,在ContextMenuView.m中,insertReactSubview:我们记住了交互到视图的关联:

- (void)insertReactSubview:(UIView *)subview atIndex:(NSInteger)atIndex
{
  [super insertReactSubview:subview atIndex:atIndex];
  if (@available(iOS 13.0, *)) {
    UIContextMenuInteraction* contextInteraction = [[UIContextMenuInteraction alloc] initWithDelegate:self];
    
    // Map interaction to its view, so that we can retrieve view by interaction later
    [interactionToViewMap setObject:subview forKey:contextInteraction]; // <-- new line

    [subview addInteraction:contextInteraction];
  }
}

然后添加一个方法,该方法将使用地图显示具有透明背景的预览:

- (nullable UITargetedPreview *)contextMenuInteraction:(UIContextMenuInteraction *)interaction previewForHighlightingMenuWithConfiguration:(UIContextMenuConfiguration *)configuration  API_AVAILABLE(ios(13.0)){
  // Set background to transparent to avoid unnecessary highlighting.
  UIPreviewParameters *params = [UIPreviewParameters alloc];
  params.backgroundColor = [UIColor clearColor];

  return [[UITargetedPreview alloc] initWithView:[interactionToViewMap objectForKey:interaction] parameters:params];
}

推荐阅读