首页 > 解决方案 > (NSTextView).visibleRect 与 SwiftUI 无法按预期工作

问题描述

我正在尝试制作一个类似 Discord 的文本字段。所以我从这里使用了一个自定义文本字段并进行了一些修改。(更改为不绘制背景)但它没有像我预期的那样消耗。我发现 (NSTextView).visibleRect.height 在两行之后没有改变。

示例动画图像

修改部分:

// ...
        // Appearance
        textView.usesAdaptiveColorMappingForDarkAppearance = true
        textView.font = nsFont
        textView.textColor = NSColor.textColor
        textView.drawsBackground = false
        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// ...

MainView 和 MessageBar:

struct MainView: View {
  var body: some View {
    MessageBar()
      .frame(minWidth: 640, maxWidth: 640, minHeight: 0, maxHeight: .infinity)
  }
}

struct MessageBar: View {

  @Environment(\.colorScheme) var colorScheme
  @State var message = NSAttributedString(string: "")

  var body: some View {
    VStack(spacing: 0) {
      Divider()
      HStack(spacing: 0) {
        Image(systemName: "plus.circle.fill").padding(8.0).padding(.leading, 8)
          .font(.title)
        MultilineTextField(NSAttributedString(string: "Message #general"), text: $message, nsFont: NSFont.preferredFont(forTextStyle: .title2)).foregroundColor(colorScheme == .light ? .black : .white)
          .font(.title2)
        Spacer()
        Image(systemName: "gift.fill").padding(8.0)
          .font(.title)
        Image(systemName: "photo.fill").padding(8.0)
          .font(.title)
        Image(systemName: "face.smiling").padding(8.0).padding(.trailing, 8)
          .font(.title)
      }.background(colorScheme == .light ? Color.init(.sRGB, red: 235 / 255, green: 237 / 255, blue: 239 / 255, opacity: 1.0) : Color.init(.sRGB, red: 64 / 255, green: 68 / 255, blue: 75 / 255, opacity: 1.0)).cornerRadius(10.0).padding(10)
    }.foregroundColor(.secondary)
  }
}

// Present the view in Playground
PlaygroundPage.current.setLiveView(MainView())

标签: swiftswiftuinsviewnstextview

解决方案


推荐阅读