Provides a SwiftUI multi-line TextView implementation including support for auto-sizing. (iOS)

Overview

TextView

Also available as a part of my SwiftUI+ Collection – just add it to Xcode 13+

Provides a SwiftUI multi-line TextView implementation with support for iOS v13+

WIP

  • Improved formatting support

Features

  • Configure all properties via modifiers
  • Multi-line text
  • Placeholder
  • No predefined design, full-flexibility to design in Swift UI
  • UIFont extensions to give you SwiftUI Font APIs
  • Auto-sizes height to fit content as you type

Example

TextView($text)
    .placeholder("Enter some text") { view in
        view.foregroundColor(.gray)
    }
    .padding(10)
    .overlay(
        RoundedRectangle(cornerRadius: 10)
            .stroke(lineWidth: 1)
            .foregroundColor(Color(.placeholderText))
    )
    .padding()

Installation

The code is packaged as a framework. You can install manually (by copying the files in the Sources directory) or using Swift Package Manager (preferred)

To install using Swift Package Manager, add this to the dependencies section of your Package.swift file:

.package(url: "https://github.com/SwiftUI-Plus/TextView.git", .upToNextMinor(from: "1.0.0"))

Other Packages

If you want easy access to this and more packages, add the following collection to your Xcode 13+ configuration:

https://benkau.com/packages.json

Comments
  • Cursor always jumps to the end when editing text

    Cursor always jumps to the end when editing text

    General Information

    • Project version: 1.1.0

    • Platform/OS version: iOS 14 and 15

    • IDE version: Xcode 13

    • Devices: iPhone 12, iPhone X

    Describe the bug

    Cursor always jumps to the end when editing text

    Steps to reproduce

    • Type "Hello World"
    • Move cursor to the beginning
    • Type "A"

    Expected behavior

    Cursor should be after "A"

    Actual behavior

    Cursor automatically moves to the end of the text.

    Video

    https://user-images.githubusercontent.com/3197049/157152747-5c38b183-233c-4a24-8b9f-0d03d98d5554.mov

    Additional context

    Since you set the text on update ui, the cursor naturally moves to the end. I have a forked version with a fix. It's something I quickly put together so I'm not entirely confident if its clean enough for a PR request (I'm also particularly new to SwiftUI) . I can send a PR if you're fine with it but if not I hope you could roll out a minor fix.

    Hope this helps. And thanks for putting this package together.

    EDIT: Replace Imgur video link with embedded video.

    bug 
    opened by teffi 9
  • Inherit font from environment

    Inherit font from environment

    Describe the feature

    Currently, the font can be configured using a custom func font(_ font: UIFont) -> TextView. SwiftUI however is built around properties exposed to the hierarchy through the environment. It would be great if TextView could adopt this and read the font from EnvironmentValues.font. Similarly it could adopt the other standardized properties exposed through the environment.

    Is your feature request related to a problem?

    TextView does not respect the .font set in the view hierarchy and needs to be manually configured.

    Proposed solution

    Remove font(_:UIFont) and read the font from the environment using @Environment. Regrettably there does not appear to be an easy way to convert a SwiftUI.Font into a UIKit.UIFont.

    opened by lhunath 5
  • Autosizing not updating in Simulator

    Autosizing not updating in Simulator

    Have you read the Contributing Guidelines?

    Yes

    General Information

    • Project version: 1.1.0

    • Platform/OS version: iOS 13.2

    • IDE version: Version 12.5.1

    • Devices: iPhone 11

    • Any related GitHub issues: Nope

    Describe the bug

    TextView's size didn't update

    Steps to reproduce

    Provide numbered steps to follow that reproduce the bug.

    1. Download Demo
    2. Delete Presentation and Browsers packages since they can't run on Xcode 12.5.1
    3. Delete PresentationDemo and ScrollViewDemo since the package has been deleted
    4. Run the project on the simulator and choose TextView

    Expected behavior

    The text2 string should be fully displayed

    Stack trace, compiler error, code snippets

    Nope

    Screenshots

    Only display the first line of string

    Additional context

    Changing TextView.swift's calculatedHeight default value to 0 fix the problem.

    bug 
    opened by retsohuang 3
  • TextView Doesn't respect

    TextView Doesn't respect "frame" height when set

    If the TextView's height is set like .frame(height: 100) the text still goes out of bounds and it also starts in the middle by default. In the cases where height of the view or parent is fixed the text should become scrollable.

    opened by kuvermaexpedia 2
  • Centering via MultilineTextAlignment modifier doesn't work

    Centering via MultilineTextAlignment modifier doesn't work

    Have you read the Contributing Guidelines?

    General Information

    • Project version: 1.1.0
    • Platform/OS version:
      iOS 14 and 15
    • IDE version: Xcode 13
    • Devices: iPhone 13
    • Any related GitHub issues: Nope

    Describe the bug

    .multilineTextAlignment(.center) doesn't center align the text

    Steps to reproduce

    Provide numbered steps to follow that reproduce the bug.

    • Create a TextView()
    • Add .multilineTextAlignment(.center) modifier
    • Preview it

    Expected behavior

    Clearly and concisely describe what you expected to happen.

    • .multilineTextAlignment(.center) should center align the text

    Screenshots

    If applicable, add screenshots, gifs, or videos to help explain your problem.

    Screen Shot 2022-06-08 at 10 03 26 AM bug 
    opened by thipokch 2
  • NSAttributedString and HTML support

    NSAttributedString and HTML support

    Hi !

    First of all, thanks for this SwiftUI multi-line TextView implementation, that's great to be able to use it as easy as it was under UIKit ;)

    I've a question, and maybe I've missed something... but when I use this Textview with an NSAttributedString containing some HTML, style is not updated but Markups are gone...

    Maybe I'm doing something wrong...

    Do you know if this has already worked for you ?

    I mean something like:

    // and then in my view

    struct MyView: View {
     
      var content: String = "This is a <b>bold</b> text."
     
      var body: some View {
          if let contentHtml = content.htmlAttributedString {
              TextView(.constant(contentHtml))
                  .isEditable(false)
                  .isSelectable(false)
                  .allowsRichText(true)
          }
      }
    }
    

    When View is displayed, I would expect the word bold to be in bold but here, <b> and </b> markups are removed but no bold anywhere...

    Have any idea about that ?

    Thank for your answer and have a nice weekend

    Jérémie

    // somewhere in my code (in a viewModel and in a String extension for example)

    extension String {
        func htmlAttributedString() -> NSAttributedString? {
            guard let data = self.data(using: .utf8) else {  return nil  }
    
            return try? NSAttributedString(
                data: data,
                options: [.documentType: NSAttributedString.DocumentType.html],
                documentAttributes: nil
            )
        }
    }
    
    bug 
    opened by jgodonQobuz 1
  • Moved attributedText setter to makeUIView

    Moved attributedText setter to makeUIView

    Have you read the Contributing Guidelines?

    Issue # https://github.com/SwiftUI-Plus/TextView/issues/5#issue-1161458839

    Describe your changes

    Clearly and concisely describe what's in this pull request. Include screenshots, if necessary.

    By moving the attributedText setter from updateUIView to makeUIView, the cursor will no longer jump to the end upon editing text.

    opened by Matt54 1
  • The text starts from the middle when a TextView has an initial height

    The text starts from the middle when a TextView has an initial height

    General Information

    • Project version: 1.1.0
    • Platform/OS version: iOS >= 14
    • IDE version: Xcode 13.4.1
    • Devices: iPhone 13 mini

    Describe the bug

    The text starts from the middle when a TextView has an initial height.

    Steps to reproduce

    1. Add a TextView
    2. Add a frame modifier to set the minimum height
    TextView($text)
        .placeholder("Description")
        .frame(minHeight: 80, maxHeight: .infinity)
    

    Expected behavior

    I'm trying to replicate the new reminder form ("Notes" field) of the default Reminder app which has a minimum height to start with and grows with the content. This library handles it like a pro except one tiny issue that the text alignment is in the middle instead of top.

    Screenshots

    CleanShot 2022-06-10 at 12 43 52@2x bug 
    opened by minimaluminium 1
  • Last character in TextView doesn't delete when the delete key is used.

    Last character in TextView doesn't delete when the delete key is used.

    Have you read the Contributing Guidelines? Yes

    General Information

    The issue I see seems very strange to me, in that deleting the last character with the delete key is a fundamental function. Yet, it doesn't work in the situation I'm using it.

    What I'm looking for is confirmation that what I'm seeing is a fundamental bug, or just something that is happening in the complex CoreData, @ObservedObject, and SwiftUI architecture.

    • Project version:
    • Platform/OS version: iOS 15.x. MacOS Cayalist

    • IDE version: Xcode 13.2.1

    • Devices: iOS and iOS simulator

    • Any related GitHub issues:

    Describe the bug

    After trying a few characters into a TextView and then deleting them using the delete key, all the characters will delete except the last. What happens to the last, is the cursor will move to the 0 position, but the last character remains.

    Also, related is if you have one or more characters and you select them and either hit the delete key, or use the Cut menu item, the text remains as described above.

    Steps to reproduce

    See above.

    Expected behavior

    The last character to delete.

    Stack trace, compiler error, code snippets

    None

    Screenshots

    None

    Additional context

    My text is coming from a CoreData text string, from an @ObservedObject var dataElement: [CoreDataObjectWithText]

    Usage: TextView(Binding(self.$dataElement.text, replacingNilWith: "")) .isEditable(true)

    Below is the custom Binding extension.

    public extension Binding where Value: Equatable { /// Creates a non-nil binding by projecting to its unwrapped value, translating nil values /// to or from the given nil value. If the source contains nil, this binding will return the /// nil value. If this binding is set to the given nil value, it will assign nil to the underlying /// source binding. /// /// This is useful if you have optional values of a type that has a logical 'empty' value of /// its own, for example String: /// /// @State var name: String? /// ... /// TextField(text: Binding($name, replacingWithNil: "")) /// /// If the name property contains nil, the text field will see an empty string. If the text field /// assigns an empty string, the name property will be set to nil. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) init(_ source: Binding<Value?>, replacingNilWith nilValue: Value) { self.init( get: { source.wrappedValue ?? nilValue }, set: { newValue in if newValue == nilValue { source.wrappedValue = nil } else { source.wrappedValue = newValue } }) }

    bug 
    opened by joemichels 0
  • Fix newline cursor issue

    Fix newline cursor issue

    Have you read the Contributing Guidelines?

    Issue

    When you input a multiline string and insert a new line somewhere in the input, the cursor will stay on the previous line whereas the height of the text view has increased (see attachment)

    Step or reproduce

    1. Input a random string
    2. Insert a new line by pressing the return key
    3. you can see the cursor stayed at the previous line, but the new line has been added.
    image

    Describe your changes

    1. Use sizeToFit to get the accurate textView size.
    2. Only update the textView size if the diff is larger than the threshold (since it is not that good to use == for floating value comparison)
    image

    Clearly and concisely describe what's in this pull request. Include screenshots, if necessary.

    opened by Cunqi 1
Owner
SwiftUI+
A collection of SwiftUI backports and more. Fully certificate signed, so please do not use any of the packages if Xcode warns otherwise.
SwiftUI+
Flutter plugin to display VGS card info using TextView or View

VGS Card Info Flutter plugin to display VGS Card info using TextView or View Installation Add the dependency in your pubspec.yaml vgscardinfo: git

Djamo Côte d'Ivoire 0 Mar 7, 2022
Library that allows you binding `enabled` property of button with textable elements (TextView, TextField)

What is NxEnabled? It's a fairly common case, when the enabled state of button depends on some textable elements such as TextView, TextField. So this

Nikita Ermolenko 33 Sep 20, 2021
An auto-layout base UITextView subclass which automatically grows with user input and can be constrained by maximal and minimal height - all without a single line of code

Deprecated This library is no longer maintained and is deprecated. The repository might be removed at any point in the future. MBAutoGrowingTextView A

Matej Balantič 125 Jan 13, 2022
An UITextView in Swift. Support auto growing, placeholder and length limit.

GrowingTextView Requirements iOS 8.0 or above Installation CocoaPods GrowingTextView is available through CocoaPods. To install it, simply add the fol

Kenneth Tsang 941 Jan 5, 2023
TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

TTextField is developed to help developers can initiate a fully standard textfield including title, placeholder and error message in fast and convinient way without having to write many lines of codes

Nguyen Duc Thinh 7 Aug 28, 2022
VKPinCodeView is simple and elegant UI component for input PIN. You can easily customise appearance and get auto fill (OTP) iOS 12 feature right from the box.

Features Variable PIN length Underline, border and custom styles The error status with / without shake animation Resetting the error status manually,

Vladimir Kokhanevich 95 Nov 24, 2022
The famous iOS search bar with auto completion feature implemented.

PRESENTATION This search bar will allow you to offer suggestions words to your users when they are looking for something using default iOS search bar.

Boisney Philippe 182 Dec 23, 2022
An auto growing text input bar for messaging apps.

ALTextInputBar An auto growing text input bar for messaging apps. Written in Swift. ALTextInputBar is designed to solve a few issues that folks usuall

Alex Littlejohn 265 Nov 15, 2022
Declarative text styles and streamlined Dynamic Type support for iOS

StyledText StyledText is a library that simplifies styling dynamic text in iOS applications. Instead of having to use attributed strings every time yo

Blue Apron 233 Oct 18, 2022
Custom emoji rendering library for iOS apps with support for GIF & still images

Custom emoji rendering library for iOS apps with support for GIF & still images - plug-in extension for UITextView - performance, cache ✅ - Made with ?? by @GetStream

Stream 244 Dec 11, 2022
A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift.

SkyFloatingLabelTextField SkyFloatingLabelTextField is a beautiful, flexible and customizable implementation of the space saving "Float Label Pattern"

Skyscanner 4k Jan 1, 2023
TextField with DropDown support using UIPickerView

IQDropDownTextField TextField with DropDown support using UIPickerView Installing Install using cocoapods. Add in your Podfile: pod 'IQDropDownTextFie

Mohd Iftekhar Qurashi 301 Jun 29, 2022
A light-weight UITextView subclass that adds support for placeholder.

RSKPlaceholderTextView A light-weight UITextView subclass that adds support for placeholder. Installation Using Swift Package Manager To add the RSKPl

Ruslan Skorb 220 Dec 17, 2022
UITextField that support currency in the right way.

PLCurrencyTextField Summary PLCurrencyTextField provides simple and user friendly support for the amount in the currency. Usage To start using the com

Łukasz Śliwiński 96 Nov 14, 2022
A UITextView subclass that adds support for multiline placeholder written in Swift.

KMPlaceholderTextView A UITextView subclass that adds support for multiline placeholder written in Swift. Usage You can set the value of the placehold

Zhouqi Mo 795 Nov 18, 2022
SwiftUI TextEdit View - A proof-of-concept text edit component in SwiftUI & CoreText.

A proof-of-concept text edit component in SwiftUI & CoreText. No UIKit, No AppKit, no UITextView/NSTextView/UITextField involved.

Marcin Krzyzanowski 80 Dec 1, 2022
Floating-textfield-swiftui - Floating textfield swiftui: Floating field with multiple icons

floating_textfield-swiftui Hey, Guys welcome to this tutorial. In this complete

Patrick 0 Jan 2, 2022
Floating-textfield-swiftui - Floating textfield With SwiftUI

floating_textfield-swiftui Hey, Guys welcome to this tutorial. In this complete

null 1 Feb 11, 2022
A SwiftUI TextField with a prompt (or placeholder) that floats above the text field when active or not empty. Requires iOS 15.

FloatingPromptTextField A prompt is the label in a text field that informs the user about the kind of content the text field expects. In a default Tex

Emilio Peláez 43 Nov 3, 2022