【问题标题】:Change color of caret SwiftUI TextField MacOS更改插入符号SwiftUI TextField MacOS的颜色
【发布时间】:2020-10-19 01:52:39
【问题描述】:

我正在尝试更改 SwiftUI 文本字段中插入符号的颜色。

我试过了:

.accentColor(Color.init(red: 0.34, green: 0.31, blue: 0.23, opacity: 1.00))

但我收到一条错误消息,指出“'accentColor' 在 macOS 中不可用”。有什么方法可以在 MacOS 中实现相同的目标? .foregroundColor 仅更改文本颜色,但不更改插入符号。

【问题讨论】:

    标签: macos colors swiftui textfield


    【解决方案1】:

    这还不可用。我向 Apple 提交了 FB8988194 以使其成为 accentColor 设置光标颜色,就像在 iOS 上一样。

    唯一的方法是使用NSViewRepresentable 并将其设置在您的NSTextField 中,如下所示:

    struct YourCustomField: NSViewRepresentable{
      func makeNSView(context: Context) -> NSTextField {
        let textField = FancyTextField()
        ...
      }
      func updateNSView(_ nsView: NSTextField, context: Context) {
        ...
      }
    }
    
    class FancyTextField: NSTextField {
      override func becomeFirstResponder() -> Bool {
        let textView = window?.fieldEditor(true, for: nil) as? NSTextView
        textView?.insertionPointColor = NSColor(named: "YourColorName")!
        
        return super.becomeFirstResponder()
      }
    }
    

    如果有人知道纯 SwiftUI 方式,我很想学习它。

    【讨论】:

      【解决方案2】:

      这是有效的解决方案。使用 Xcode 12b 测试

      if #available(OSX 10.16, *) {
          TextField("Placeholder", text: self.$text)
             .accentColor(.red)
      } else {
          TextField("Placeholder", text: self.$text)
             .colorMultiply(.red)
      }
      

      【讨论】:

        猜你喜欢
        • 2013-08-28
        • 1970-01-01
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        • 2015-09-07
        • 2012-07-21
        • 2022-01-22
        相关资源
        最近更新 更多