You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在contextMenu激活时将选中文本的背景色从透明改为黑色?

修改长按Text显示ContextMenu时的选中背景色

当长按Text("Long press for menu")唤起ContextMenu时,想要修改文本被选中时的背景色,可通过以下两种方案实现:

方案1:全局修改选中背景色

SwiftUI中文本长按选中的样式由UIKit组件控制,可在App启动时通过UIAppearance全局配置:

import SwiftUI

@main
struct YourApp: App {
    init() {
        // 设置选中背景色(带透明度的黄色示例)
        UITextSelectionView.appearance().backgroundColor = UIColor.systemYellow.withAlphaComponent(0.3)
        // 可选:修改选中文本颜色
        UITextSelectionView.appearance().textColor = UIColor.systemRed
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        Text("Long press for menu")
            .contextMenu {
                Button {
                    print("Pills selected")
                } label: {
                    Label("Pills", systemImage: "pills")
                }

                Button {
                    print("Heart selected")
                } label: {
                    Label("Heart rate", systemImage: "heart")
                }

                Button {
                    print("ECG selected")
                } label: {
                    Label("ECG", systemImage: "waveform.path.ecg")
                }
            }
    }
}

方案2:局部自定义长按逻辑(避免系统默认选中样式)

如果只想针对当前Text修改,可自定义长按手势,手动控制高亮状态和菜单弹出:

struct ContentView: View {
    @State private var isHighlighted = false
    
    var body: some View {
        Text("Long press for menu")
            .background(isHighlighted ? Color.yellow.opacity(0.3) : Color.clear)
            .onLongPressGesture(minimumDuration: 0.5) {
                isHighlighted = true
                // 构建自定义菜单
                let menu = UIMenu(title: "", children: [
                    UIAction(title: "Pills", image: UIImage(systemName: "pills")) { _ in
                        print("Pills selected")
                        isHighlighted = false
                    },
                    UIAction(title: "Heart rate", image: UIImage(systemName: "heart")) { _ in
                        print("Heart selected")
                        isHighlighted = false
                    },
                    UIAction(title: "ECG", image: UIImage(systemName: "waveform.path.ecg")) { _ in
                        print("ECG selected")
                        isHighlighted = false
                    }
                ])
                UIApplication.shared.sendAction(#selector(UIResponder.showMenu(_:)), to: nil, from: menu, for: nil)
            }
            .onTapGesture {
                isHighlighted = false
            }
    }
}

说明

  • 方案1全局生效,会改变所有文本的选中样式;
  • 方案2仅作用于当前Text,完全自定义高亮效果,逻辑更灵活。

内容的提问来源于stack exchange,提问作者artit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:22:18