向 TextEditor 添加水平填充,但防止其在内部移动滚动条

Bre*_*mbs 6 text-editor ios swift swiftui

我正在使用一个文本编辑器,我想为其添加水平填充,以便文本不会粘在任一边缘。但是,问题是,如果我包含它,并且其中的文本是可滚动的,那么滚动条不会位于最右侧,而是会按填充量移动到内部。

        TextEditor(text: $text)
         .background(Color.white)
         .foregroundColor(Color.black)
         .frame(maxWidth: .infinity, maxHeight: .infinity)
         .customFont(.body)
         .lineSpacing(8)
         .padding(.leading)
         .padding(.trailing)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Asp*_*eri 8

您向外部框架添加了填充,但需要缩进内部文本容器。可能的解决方案(因为 TextEditor 实际上是 UITextView)使用外观。所以解决方案是在父视图中添加以下内容TextEditor

init() {
    UITextView.appearance().textContainerInset = 
         UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)   // << !!
}

// ... other code

    TextEditor(text: $text)
     .background(Color.white)
     .foregroundColor(Color.black)
     .frame(maxWidth: .infinity, maxHeight: .infinity)
     .customFont(.body)
     .lineSpacing(8)
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 12 / iOS 14 进行测试

  • 如何在 macOS 上做同样的事情? (5认同)