SwiftUI视图背景内的UITextView和深色模式的边框颜色(窗体)

时间:2020-02-04 22:44:47

标签: ios swift xcode uitextview swiftui

我正在尝试使UITextView看起来与(SwiftUI)TextField相同,UITextView代码如下:

...
func makeUIView(context: UIViewRepresentableContext<TextView>) -> UITextView {
  let textView = UITextView()

  textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) 
  textView.text = placeholderText
  textView.textColor = .placeholderText
  textView.backgroundColor = .systemBackground
  textView.layer.borderColor = UIColor.placeholderText.cgColor
  textView.layer.borderWidth = 1
  textView.layer.cornerRadius = 6

  return textView
}
...

完整代码类似于this

在窗体中,在轻模式下看起来不错: enter image description here

但是,在黑暗模式下的表单中:

enter image description here

我怎么了?

textView.backgroundColor = .systemBackground
textView.layer.borderColor = UIColor.placeholderText.cgColor

1 个答案:

答案 0 :(得分:0)

我明白了。我拥有的UITextView位于UIViewController中(以更好地控制尺寸)

该设置不显示灰色背景。

public class CustomTextView: UIViewController {
    var textView: UITextView!

    init() {
        super.init(nibName: nil, bundle: nil)
        self.textView = UITextView(frame: .zero)
        self.textView.frame = self.view.bounds
        self.view.addSubview(textView)
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        textView = UITextView(frame: .zero)
        textView.frame = self.view.bounds
        self.view.addSubview(textView)
    }
}

然后在您的UIViewRepresentable

public func makeUIViewController(context: UIViewControllerRepresentableContext<TextViewController_UI>) -> TextViewController_UI.CustomTextView {
    let textViewCont = CustomTextView()

    textViewCont.textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
    textViewCont.textView.text = "placeholder"
    textViewCont.textView.textColor = .placeholderText
    textViewCont.textView.backgroundColor = .systemBackground
    textViewCont.textView.layer.borderColor = UIColor.placeholderText.cgColor
    textViewCont.textView.layer.borderWidth = 1
    textViewCont.textView.layer.cornerRadius = 6
    return textViewCont
}