SwiftUI中TextEditor的透明背景。

5
我正在使用SwiftUI为iOS、iPadOS和macOS构建应用程序,需要一个带有透明背景的TextEditor。
这个问题以前已经被问过了,我找到了一个针对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上为TextEditor获得透明背景的方法吗?
此外,这个问题已经在这里特别提到了macOS:Changing TextEditor background color in SwiftUI for macOS,但没有给出有效的答案。
1个回答

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
    }
}

输入图像描述信息


3
火腿救星!如果您需要支持iOS 16之前/ macOS 13之前的解决方案,这是到目前为止最好的选择。 - stef
UITextView是否有类似的解决方案?我尝试过了,但UITextView没有drawsBackground属性。没有这个属性,当输入框出现时,它显示正确的颜色,但用户输入一些文本后,颜色会重置为白色。 - Renars

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接