SwiftUI 中文本编辑器的透明背景 [英] Transparent Background for TextEditor in SwiftUI
问题描述
我正在使用SwiftUI构建适用于iOS,iPadOS和macOS的应用程序,我需要具有透明背景的TextEditor.
这个问题已经被问过了,我为iOS/iPadOS找到了一个很好的答案(
I am using SwiftUI to build an app for iOS, iPadOS and macOS and I need a TextEditor with a transparent background.
This question has been asked before and I found a good answer for iOS/iPadOS (Change background color of TextEditor in SwiftUI), but none for macOS.
This is the code I have based on the link above that works perfectly for iOS and iPadOS:
TextEditor(text: $text)
.foregroundColor(.black)
.onAppear {
#if os(macOS)
// ??
#else
UITextView.appearance().backgroundColor = .clear
#endif
}
NSTextView
doesn't appear to have an equivalent to UITextView.appearance()
, so I'm not entirely sure what to do there.
Using .background(Color.clear)
also doesn't work:
TextEditor(text: $text)
.foregroundColor(.black)
.background(Color.clear)
.onAppear {
#if os(macOS)
// ??
#else
UITextView.appearance().backgroundColor = .clear
#endif
}
Does anyone know of a way to get a transparent background for a TextEditor on macOS?
Also, this question has already been asked specifically about macOS here: Changing TextEditor background color in SwiftUI for macOS, but no answer that works given.
Here is a possible work around for this. The extension sets all of your TextViews background to .clear
and then you are able to change the background color with .background()
modifier.
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
}
}
这篇关于SwiftUI 中文本编辑器的透明背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!