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

时间:2020-10-29 12:25:56

标签: ios swift swiftui text-editor

我正在使用一个TextEditor,我想为其添加水平填充,以使文本不会粘在任一边缘上。但是,问题是如果我包含它,并且其中的文本是可滚动的,则滚动条不会位于最右边,而是已向内移动了填充量。

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

enter image description here

1 个答案:

答案 0 :(得分:2)

您已将填充添加到外部框架,但是需要缩进内部文本容器。使用外观的可能解决方案(因为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)

通过Xcode 12 / iOS 14测试