SwiftUI 中文本编辑器的透明背景

问题描述 投票:0回答:2

我正在使用 SwiftUI 构建适用于 iOS、iPadOS 和 macOS 的应用程序,我需要一个具有透明背景的文本编辑器。

这个问题之前已经被问过,我找到了一个适用于 iOS/iPadOS 的好答案(更改 SwiftUI 中 TextEditor 的背景颜色),但没有适用于 macOS。

这是我根据上面的链接编写的代码,非常适合 iOS 和 iPadOS:

TextEditor(text: $text)
  .foregroundColor(.black)
  .onAppear {
      #if os(macOS)
      // ??
      #else
      UITextView.appearance().backgroundColor = .clear
      #endif
  }

NSTextView
似乎没有相当于
UITextView.appearance()
,所以我不完全确定在那里做什么。

使用

.background(Color.clear)
也不起作用:

TextEditor(text: $text)
  .foregroundColor(.black)
  .background(Color.clear)
  .onAppear {
      #if os(macOS)
      // ??
      #else
      UITextView.appearance().backgroundColor = .clear
      #endif
  }

有谁知道如何在 macOS 上为文本编辑器获取透明背景吗?

此外,这个问题已经在这里专门针对 macOS 提出:Changing TextEditor background color in SwiftUI for macOS,但没有给出有效的答案。

swift macos swiftui nstextview
2个回答
26
投票

这是一个可能的解决方法。该扩展将所有 TextView 背景设置为

.clear
,然后您可以使用
.background()
修饰符更改背景颜色。

import SwiftUI

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            backgroundColor = .clear //<<here clear
            drawsBackground = true
        }

    }
}

struct ContentView: View {
    
    @State var string: String = ""
    
    var body: some View {
        TextEditor(text: $string)
            .textFieldStyle(PlainTextFieldStyle())
            .background(Color.red) //<< here red
    }
}


0
投票

截至 2024 年 1 月 26 日,我无法获得可接受的工作答案。

当我添加扩展代码时,我总是收到一个错误,

NSTextView
不在范围内:

在范围内找不到类型“NSTextView”

但是,我偶然发现了一种(可能)更简单的方法来设置文本编辑器背景颜色。

我刚刚做了两件事:

  1. 我将控件的不透明度设置为0.8。
    .opacity(0.8)
  2. 我将背景设置为我想要的颜色
    .background(Color.blue)

我的最终代码看起来像这样:

TextEditor(text: Binding(get: { userTask.note ?? "" }) {
            userTask.note = $0
        })
        .opacity(0.8)
        .background(Color.blue)

它看起来像这样:

© www.soinside.com 2019 - 2024. All rights reserved.