Ale*_*ert 3 macos nstextview swift swiftui
我正在使用 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
}
Run Code Online (Sandbox Code Playgroud)
NSTextView
似乎没有相当于UITextView.appearance()
,所以我不完全确定在那里做什么。
使用.background(Color.clear)
也不起作用:
TextEditor(text: $text)
.foregroundColor(.black)
.background(Color.clear)
.onAppear {
#if os(macOS)
// ??
#else
UITextView.appearance().backgroundColor = .clear
#endif
}
Run Code Online (Sandbox Code Playgroud)
有谁知道在 macOS 上为 TextEditor 获取透明背景的方法?
此外,这里已经专门针对 macOS 询问了这个问题:Changing TextEditor background color in SwiftUI for macOS,但没有给出有效的答案。
这是一个可能的解决方法。该扩展将所有 TextViews 背景设置为.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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
780 次 |
最近记录: |