簡體   English   中英

SwiftUI - 有沒有辦法創建一個只讀的文本編輯器?

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

我在 SwiftUI 中使用 TextEditor 來顯示長文本的內容。

我希望這是只讀的,但只要我點擊它,鍵盤就會彈出。

有沒有辦法讓 TextEditor 成為只讀的並且當用戶點擊它時看不到鍵盤?

我試過.disabled()但這不好,因為它會阻止 controller 滾動,就像我說的,controller 包含長文本。

Text不好,因為它不滾動。

DonMag 的解決方案不能 select 文本。 相反,只需使用.constant(...)

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

滾動文本的非常基本的示例:

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

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

這是一個帶有一些長文本的示例:

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 | SwiftUI 2

像魅力一樣輕松!


方式一:假裝訂

  1. 創建文本變量
  2. 創建假綁定
let text: String
var textBind: Binding<String> { Binding(get: { text }, set: { _ in }) }


//usage:
TextEditor(text: textBind )

結果 - 只讀文本編輯器。


方式二:內省

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

簡單的示例解決方案

只需像這樣使用.constant()綁定,您將保持完整的 TextEditor 功能(滾動、選擇復制/粘貼等):

TextEditor(text: .constant(text))

下面的完整示例代碼。 您不需要使用視圖 model 但我認為它更干凈一些。 我正在構建一個 swift 語法熒光筆應用程序,用於我在www.theswift.dev上的博客文章,而一個簡單的適用於 macOS 的 SwiftUI 應用程序似乎是我快速粘貼多行代碼並從第二個復制結果的好方法文本編輯器。 使用 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