简体   繁体   English

SwiftUI - 有没有办法创建一个只读的文本编辑器?

[英]SwiftUI - Is there a way to create a read-only TextEditor?

I am using a TextEditor in SwiftUI to display the contents of a long text.我在 SwiftUI 中使用 TextEditor 来显示长文本的内容。

I want this to be read-only but any time I tap on it, the keyboard pops up.我希望这是只读的,但只要我点击它,键盘就会弹出。

Is there a way to make the TextEditor read-only and do not see the keyboard when the user taps on it?有没有办法让 TextEditor 成为只读的并且当用户点击它时看不到键盘?

I have tried .disabled() but this is not good because it prevents the controller from scrolling and like I said, the controller contains a long text.我试过.disabled()但这不好,因为它会阻止 controller 滚动,就像我说的,controller 包含长文本。

Text is not good because it does not scroll. Text不好,因为它不滚动。

DonMag's solution can't select text. DonMag 的解决方案不能 select 文本。 Instead, just use .constant(...) .相反,只需使用.constant(...)

TextEditor(text: .constant(self.text))

Very basic example of scrolling text:滚动文本的非常基本的示例:

struct ContentView: View {
    @State var content = "Long text here..."

    var body: some View {
        ScrollView {
            VStack {
                Text(content)
                    .lineLimit(nil)
            }.frame(maxWidth: .infinity)
        }
    }
}

Here's an example with some long text:这是一个带有一些长文本的示例:

import SwiftUI

struct ContentView: View {
    @State var content =
        """
    Label

    A label can contain an arbitrary amount of text, but UILabel may shrink, wrap, or truncate the text, depending on the size of the bounding rectangle and properties you set. You can control the font, text color, alignment, highlighting, and shadowing of the text in the label.

    Button

    You can set the title, image, and other appearance properties of a button. In addition, you can specify a different appearance for each button state.

    Segmented Control
    
    The segments can represent single or multiple selection, or a list of commands.
    
    Each segment can display text or an image, but not both.
    
    Text Field
    
    Displays a rounded rectangle that can contain editable text. When a user taps a text field, a keyboard appears; when a user taps Return in the keyboard, the keyboard disappears and the text field can handle the input in an application-specific way. UITextField supports overlay views to display additional information, such as a bookmarks icon. UITextField also provides a clear text control a user taps to erase the contents of the text field.

    Slider
    
    UISlider displays a horizontal bar, called a track, that represents a range of values. The current value is shown by the position of an indicator, or thumb. A user selects a value by sliding the thumb along the track. You can customize the appearance of both the track and the thumb.
    
    Switch
    
    Displays an element that shows the user the boolean state of a given value.  By tapping the control, the state can be toggled.

    Activity Indicator View
    
    Used to indicate processing for a task with unknown completion percentage.
    
    Progress View
    
    Shows that a lengthy task is underway, and indicates the percentage of the task that has been completed.

    Page Control
    
    UIPageControl indicates the number of open pages in an application by displaying a dot for each open page. The dot that corresponds to the currently viewed page is highlighted. UIPageControl supports navigation by sending the delegate an event when a user taps to the right or to the left of the currently highlighted dot.
    
    Stepper
    
    Often combined with a label or text field to show the value being incremented.

    Horizontal Stack View
    
    An UIStackView creates and manages the constraints necessary to create horizontal or vertical stacks of views. It will dynamically add and remove its constraints to react to views being removed or added to its stack. With customization it can also react and influence the layout around it.
    
    Vertical Stack View
    
    An UIStackView creates and manages the constraints necessary to create horizontal or vertical stacks of views. It will dynamically add and remove its constraints to react to views being removed or added to its stack. With customization it can also react and influence the layout around it.

    Table View
    
    Coordinates with a data source and delegate to display a scrollable list of rows. Each row in a table view is a UITableViewCell object.
    
    The rows can be grouped into sections, and the sections can optionally have headers and footers.
    
    The user can edit a table by inserting, deleting, and reordering table cells.
    
    Table View Cell
    
    Defines the attributes and behavior of cells in a table view. You can set a table cell's selected-state appearance, support editing functionality, display accessory views (such as a switch control), and specify background appearance and content indentation.

    Image View
    
    Shows an image, or series of images as an animation.
    
    Collection View
    
    Coordinates with a data source and delegate to display a scrollable collection of cells. Each cell in a collection view is a UICollectionViewCell object.
    
    Collection views support flow layout as well a custom layouts, and cells can be grouped into sections, and the sections and cells can optionally have supplementary views.
    """
    
    var body: some View {
        ScrollView {
            VStack {
                Text(content)
                    .lineLimit(nil)
            }.frame(maxWidth: .infinity)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2021 | 2021 | SwiftUI 2 SwiftUI 2

Easy like a charm!像魅力一样轻松!


WAY 1: fake binding方式一:假装订

  1. create text variable创建文本变量
  2. create fake binding创建假绑定
let text: String
var textBind: Binding<String> { Binding(get: { text }, set: { _ in }) }


//usage:
TextEditor(text: textBind )

as result - read only Text Editor.结果 - 只读文本编辑器。


Way 2: Introspect方式二:内省

TextEditor(text: $text )
    .introspectTextView{ $0.isEditable = false }

Easy Solution With Example简单的示例解决方案

Just use a .constant() binding like this and you'll maintain full TextEditor functionality (scrolling, selection for copy/paste, etc):只需像这样使用.constant()绑定,您将保持完整的 TextEditor 功能(滚动、选择复制/粘贴等):

TextEditor(text: .constant(text))

Full example code below.下面的完整示例代码。 You don't need to use a view model but I think it's a little more clean.您不需要使用视图 model 但我认为它更干净一些。 I was building a swift syntax highlighter app to use for my blog posts on www.theswift.dev , and a simple SwiftUI app for macOS seemed like a nice way for me to quickly paste in multi-line code and copy the result from a second TextEditor.我正在构建一个 swift 语法荧光笔应用程序,用于我在www.theswift.dev上的博客文章,而一个简单的适用于 macOS 的 SwiftUI 应用程序似乎是我快速粘贴多行代码并从第二个复制结果的好方法文本编辑器。 Using Swift Package Manager I pulled in the awesome Splash library to use its HTML highlighting.使用 Swift Package 管理器,我拉入了很棒的Splash库以使用其 HTML 突出显示。

import SwiftUI
import Splash

class ViewModel: ObservableObject {
    @Published var text = ""
    @Published var highlightedText = ""
}

struct ContentView: View {
    
    @ObservedObject var viewModel = ViewModel()
    
    let highlighter = SyntaxHighlighter(format: HTMLOutputFormat())
    
    var body: some View {
        VStack {
            TextEditor(text: $viewModel.text)
                .overlay {
                    Text(viewModel.text.isEmpty ? "Enter Swift code to begin highlighting" : "")
                        .allowsHitTesting(false)
                }
            Button {
                highlightText()
            } label: {
                Text("Highlight")
            }
            .keyboardShortcut(.return)

            TextEditor(text: .constant(viewModel.highlightedText))
        }
        .padding()
    }
    
    func highlightText() {
        viewModel.highlightedText = highlighter.highlight(viewModel.text)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM