An UITextView in Swift. Support auto growing, placeholder and length limit.

Overview

GrowingTextView

Version License Platform Language Language Language Language

Requirements

iOS 8.0 or above

Installation

CocoaPods

GrowingTextView is available through CocoaPods. To install it, simply add the following line to your Podfile:

Swift 5.0

pod 'GrowingTextView', '0.7.2'

Swift 4.2

pod 'GrowingTextView', '0.6.1'

Swift 4.1

pod 'GrowingTextView', '~> 0.5'

Swift 3

pod 'GrowingTextView', '~> 0.4'

Swift 2.3 (Stopped update since Sep 2016)

pod 'GrowingTextView', :git => 'https://github.com/KennethTsang/GrowingTextView.git', :branch => 'swift2'

Carthage

GrowingTextView is also available through Carthage. To install it, add the following line to your Cartfile:

Swift 5.0

github "KennethTsang/GrowingTextView" ~> 0.7

Swift 4.2

github "KennethTsang/GrowingTextView" ~> 0.6

Swift 4.1

github "KennethTsang/GrowingTextView" ~> 0.5

Swift 3

github "KennethTsang/GrowingTextView" ~> 0.4

Swift 2.3 (Stopped update since Sep 2016)

github "KennethTsang/GrowingTextView" "swift2"

Manually

Copy GrowingTextView.swift into your project.

Usage

Example

GrowingTextview is just a textview, download the example to see how to use it as a input toolbar like other instant messaging apps.

Using GrowingTextview programmatically

let textView = GrowingTextView()
textView.delegate = self
addSubview(textView)

Using GrowingTextview in Storyboard

  1. Drag a TextView into Storyboard.
  2. Set class to "GrowingTextView".
  3. Set delegate to it's view controller.
automaticallyAdjustsScrollViewInsets

Sometime the view controller may incorrectly adjust the inset of textview automatically. To avoid this, set automaticallyAdjustsScrollViewInsets to false

override func viewDidLoad() {
	super.viewDidLoad()
	automaticallyAdjustsScrollViewInsets = false
}

Customization

Parameter Type Description Default
maxLength Int Maximum text length. Exceeded text will be trimmed. 0 means no limit. 0
trimWhiteSpaceWhenEndEditing Bool Trim white space and new line characters when textview did end editing. true
placeholder String? Placeholder text. nil
placeholderColor UIColor Placeholder text color. UIColor(white: 0.8, alpha: 1.0)
attributedPlaceholder NSAttributedString? Attributed Placeholder text. nil
minHeight CGFloat Minimum height of textview. 0.0
maxHeight CGFloat Maximum height of textview. 0.0

Examples

textView.maxLength = 140
textView.trimWhiteSpaceWhenEndEditing = false
textView.placeholder = "Say something..."
textView.placeholderColor = UIColor(white: 0.8, alpha: 1.0)
textView.minHeight = 25.0
textView.maxHeight = 70.0
textView.backgroundColor = UIColor.whiteColor()
textView.layer.cornerRadius = 4.0

Animation

  1. Adopt GrowingTextViewDelegate instead of UITextViewDelegate.
  2. Implement textViewDidChangeHeight.
  3. Call layoutIfNeeded() on superview inside the animation.
class ViewController: UIViewController, GrowingTextViewDelegate {
	func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
	   UIView.animate(withDuration: 0.2) {
	       self.view.layoutIfNeeded()
	   }
	}
}

Delegate

GrowingTextViewDelegate is inherited from UITextViewDelegate. You may use it's delegate function as a normal UITextView.

class ViewController: UIViewController, GrowingTextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
    	...
    }
    func textViewDidEndEditing(_ textView: UITextView) {
    	...
    }
}

Check out UITextViewDelegate here: https://developer.apple.com/reference/uikit/uitextviewdelegate

Author

Kenneth Tsang, [email protected]

License

GrowingTextView is available under the MIT license. See the LICENSE file for more info.

Comments
  • Updating maxHeight should cause layoutSubviews to be called immediately

    Updating maxHeight should cause layoutSubviews to be called immediately

    Hi @KennethTsang! 😄 First off, great job with this library! As the title suggests, I am suggesting that when the maxHeight is updated, that layoutSubviews be called immediately to update the heightConstraint. For my use case, I am working on something where the maxHeight of the text view is constantly changing depending on certain factors within my app.

    Line 100 in GrowingTextView.swift will need to be removed because even though the text and width may be the same, the maxHeight may not be.

    Let me know what you think! 👍

    opened by Daltron 9
  • Not working on os11 ?

    Not working on os11 ?

    Just copied the source into my project, dropped a textview onto my viewcontroller, changed the class to GrowingTextView and when I run, the keyboard overlays the textview?

    So in my case I have a tableview and want to add this at the bottom. I created a view, dropped a textview in it (just as in the example 2). What I don't understand is how this resizes the tableview while the keyboard is open?

    opened by justdan0227 7
  • Use inside UITableViewCell

    Use inside UITableViewCell

    Hello, thanks for the great library!

    I'm trying to use it inside UITableViewCell with all edges pinned to edges of cell, so tableviewcell should grow height with textview size change. I've adopted self sizing textview, as described here http://candycode.io/self-sizing-uitextview-in-a-uitableview-using-auto-layout-like-reminders-app/

    While it works fine with regular UITextView, when I change it to GrowingTextView - I constantly receive following error with constraints (it seems GrowingTextView tries to update height costraint before it should do so):

    [LayoutConstraints] Unable to simultaneously satisfy constraints.
    	Probably at least one of the constraints in the following list is one you don't want. 
    	Try this: 
    		(1) look at each constraint and try to figure out which you don't expect; 
    		(2) find the code that added the unwanted constraint or constraints and fix it. 
    (
        "<NSLayoutConstraint:0x60000009da10 UILabel:0x7fa954e23b00'\U0421\U043e\U0445\U0440\U0430\U043d\U0438\U0442\U044c \U0432 \U0448\U0430\U0431\U043b\U043e\U043d\U044b'.height == 30   (active)>",
        "<NSLayoutConstraint:0x61000009f1d0 V:[UILabel:0x7fa954e23b00'\U0421\U043e\U0445\U0440\U0430\U043d\U0438\U0442\U044c \U0432 \U0448\U0430\U0431\U043b\U043e\U043d\U044b']-(7)-|   (active, names: '|':UITableViewCellContentView:0x7fa954e224c0 )>",
        "<NSLayoutConstraint:0x61000009e0a0 V:|-(7)-[UILabel:0x7fa954e23b00'\U0421\U043e\U0445\U0440\U0430\U043d\U0438\U0442\U044c \U0432 \U0448\U0430\U0431\U043b\U043e\U043d\U044b']   (active, names: '|':UITableViewCellContentView:0x7fa954e224c0 )>",
        "<NSLayoutConstraint:0x61800009afe0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fa954e224c0.height == 43.5   (active)>"
    )
    
    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x60000009da10 UILabel:0x7fa954e23b00'Сохранить в шаблоны'.height == 30   (active)>
    
    opened by OSemenovBoyarka 4
  • Dynamic Text View - Lines of text shifting up

    Dynamic Text View - Lines of text shifting up

    I have some sample code below where I try to mimic the dynamic text view calculation like your code. My question is how is the top inset addressed with respect to the text container? When I get to about the second line, my first line shifts up pretty much to very edge of the top frame of Text View. I want the text to stay center to the line height.

    import UIKit
    
    class ViewController: UIViewController, UITextViewDelegate {
    
        @IBOutlet weak var textView: UITextView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            self.textView.delegate = self
            self.textView.backgroundColor = .lightGray
        }
        
        func textViewDidChange(_ textView: UITextView) {
            self.calculateSize()
        }
    
        func calculateSize() {
            let fixedWidth = textView.frame.size.width
            textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
            let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
            var newFrame = textView.frame
            newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
            textView.frame = newFrame
        }
    }
    
    
    opened by jboo1212 3
  • [Bug] Crashes every time TextView grows if you don't declare textViewDidChangeHeight from the Delegate

    [Bug] Crashes every time TextView grows if you don't declare textViewDidChangeHeight from the Delegate

    If you don't define the textViewDidChangeHeight "optional" method from the delegate, it crashes. So i don't actually need that method from the delegate. So for now, i'm calling the method, but leave it empty.

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Vilger.MessageViewController textViewDidChangeHeight:height:]: unrecognized selector sent to instance 0x7fc978d23720' *** First throw call stack: ( 0 CoreFoundation 0x0000000109357d4b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x0000000108db921e objc_exception_throw + 48 2 CoreFoundation 0x00000001093c7f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x00000001092dce1e forwarding + 526 4 CoreFoundation 0x00000001092dcb88 _CF_forwarding_prep_0 + 120 5 GrowingTextView 0x000000010574bcf6 TFC15GrowingTextView15GrowingTextView14layoutSubviewsfT_T + 1958 6 GrowingTextView 0x000000010574bf62 TToFC15GrowingTextView15GrowingTextView14layoutSubviewsfT_T + 34 7 UIKit 0x0000000106ca0ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237 8 QuartzCore 0x0000000105d5dbf8 -[CALayer layoutSublayers] + 146 9 QuartzCore 0x0000000105d51440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 10 QuartzCore 0x0000000105d512be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 11 QuartzCore 0x0000000105cdf318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 12 QuartzCore 0x0000000105d0c3ff _ZN2CA11Transaction6commitEv + 475 13 QuartzCore 0x0000000105c677f7 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 611 14 CoreFoundation 0x00000001092e9db4 CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 20 15 CoreFoundation 0x00000001092e9a43 __CFRunLoopDoTimer + 1075 16 CoreFoundation 0x00000001092e95ca __CFRunLoopDoTimers + 250 17 CoreFoundation 0x00000001092e12f1 __CFRunLoopRun + 2065 18 CoreFoundation 0x00000001092e0884 CFRunLoopRunSpecific + 420 19 GraphicsServices 0x000000010c4fea6f GSEventRunModal + 161 20 UIKit 0x0000000106bdbc68 UIApplicationMain + 159 21 Vilger 0x000000010363e58f main + 111 22 libdyld.dylib 0x000000010aee568d start + 1 )

    opened by nuno-vieira 3
  • App crashed on XCode 11.2

    App crashed on XCode 11.2

    I have app crashed by using this library, the reason is "Could not instantiate class named _UITextLayoutView because no class named _UITextLayoutView was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target)". If there is any body have same issue please let me know how to resolved this issue, thanks

    opened by sailendra85 2
  • ReadMe says Swift 5 Podspec sets Swift 4

    ReadMe says Swift 5 Podspec sets Swift 4

    It's mentioned in Readme.md file that for Swift 5 you need to use 0.7 version. But if i use that version. It's settings still shows Swift 4 as language and compiler throws error that Swift 5 conversion is available

    opened by mihirpmehta 2
  • Adjusting Text View Inset

    Adjusting Text View Inset

    Having an issue when wanting to adjust the inset of the text. I'd like to add a padding to the inside so the text starts further away from the edge of the text view. Currently the text indicator is too close to edge.

    Current Screen Shot 2019-04-01 at 9 48 35 PM

    Trying to change the content inset gives this outcome:

    messageField.textContainerInset = UIEdgeInsets(top: 0, left: 0.5, bottom: 0, right: 0)
    

    Screen Shot 2019-04-01 at 9 43 02 PM

    Ideas?

    opened by chuninator 2
  • Autolayout Failed to Render

    Autolayout Failed to Render

    error: IB Designables: Failed to render and update auto layout status for UIView (i5M-Pr-FkT): dlopen(GrowingTextView.framework, 1): no suitable image found. Did find: GrowingTextView.framework: required code signature missing for 'GrowingTextView.framework'

    getting this error for days and nothing could fix it , any idea ?

    opened by Mahan3340 2
  • Example 2 & 3 failed under iOS 11

    Example 2 & 3 failed under iOS 11

    Built directly on top of example storyboard, example 1 runs fine, but both 2 & 3 failed.

    Both would complain of height constraints missing. Yet after resolving conflicts by adding missing constraints, textView wouldn't grow as expected. Wondering whether we need to do something more for iOS 11.

    opened by bayareahank 2
  •  infinite layoutSubviews loop

    infinite layoutSubviews loop

    Hi, thanks for good work. But... bug: just enter fast some lines like this: http://joxi.ru/DrlBkR0i4bW4j2

    layoutSubviews infinite calls, CPU usage 100%

    opened by vitalrum 2
  • Ambiguous use of 'attributedPlaceholder'

    Ambiguous use of 'attributedPlaceholder'

    I want to add attributed placeholder to textView which if type GrowingTextView. But it shows error "Ambiguous use of "attributedPlaceholder". Screenshot 2020-08-11 at 5 13 15 PM I guess the name of the placeholder attribute should be changed to something different as UItextView already has placeholder attribute.

    opened by Yashraj4394 1
  • Would not work unless I added setNeedsLayout

    Would not work unless I added setNeedsLayout

    I've been using your library for years without problems. Recently I had to resume a project which I haven't touched in several months, so I'm not sure if this is now an iOS 13.3 issue or what, but the textview would just not work.

    Until I went into the soucecode of the GrowingTextView and added setNeedsLayout here:

        // Limit the length of text
        @objc func textDidChange(notification: Notification) {
            if let sender = notification.object as? GrowingTextView, sender == self {
                if maxLength > 0 && text.count > maxLength {
                    let endIndex = text.index(text.startIndex, offsetBy: maxLength)
                    text = String(text[..<endIndex])
                    undoManager?.removeAllActions()
                }
                setNeedsDisplay()
                setNeedsLayout() <-- HERE
            }
        }
    

    Then everything works as expected. Is this normal? If not, why could it be happening?

    opened by jlubeck 1
  • Found a bug that does not change its vertical size.

    Found a bug that does not change its vertical size.

    If you press the backspace quickly and continuously, there are bugs that temporarily do not change the vertical size. Can you fix the problem? Thank you.

    opened by jasudev 0
  • Not able to use globe button to change keyboard

    Not able to use globe button to change keyboard

    In my case, I have chat screen which supports arabic and english language and when I am using your lib, it doesn't showing globe button to change keyboard. Is there some settings to change? Also can't paste arabic or emoji in textview.

    download

    opened by NirajCapermint 1
Releases(0.7.2)
Owner
Kenneth Tsang
Kenneth Tsang
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
DGPlaceholderTextView - A light-weight UITextView that supports for placeholder

DGPlaceholderTextView Requirements Installation Usage Properties DGPlaceholderTe

donggyu 5 Jan 26, 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
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
A customisable view for entering arbitrary length pins, codes or passwords in iOS. Supports iOS 12 one time codes.

CBPinEntryView CBPinEntryView is a view written in Swift to allow easy and slick entry of pins, codes or passwords. It allows backspacing, dismissal o

Chris Byatt 183 Dec 5, 2022
📝 The next in the generations of 'growing textviews' optimized for iOS 8 and above.

NextGrowingTextView The next in the generations of 'growing textviews' optimized for iOS 8 and above. As a successor to HPGrowingTextView, NextGrowing

Muukii 1.7k Dec 25, 2022
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
DTTextField is a custom textfield with floating placeholder and error label

DTTextField Introduction DTTextField is a UITextField library with floating placeholder and error label. Floating placeholder inspired from JVFloatLab

Dhaval Thanki 310 Jan 5, 2023
HTYTextField A UITextField with bouncy placeholder.

HTYTextField - A UITextField with bouncy placeholder. Screenshot Installation CocoaPods Add the dependency to your Podfile

Hanton Yang 312 Nov 13, 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
Simple placeholder move textfield

PlaceholderTextField Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 11.0 o

null 6 Mar 9, 2022
Placeholder views based on content, loading, error or empty states

StatefulViewController A protocol to enable UIViewControllers or UIViews to present placeholder views based on content, loading, error or empty states

Alexander Schuch 2.1k Dec 8, 2022
Provides a SwiftUI multi-line TextView implementation including support for auto-sizing. (iOS)

TextView Also available as a part of my SwiftUI+ Collection – just add it to Xcode 13+ Provides a SwiftUI multi-line TextView implementation with supp

SwiftUI+ 51 Jan 3, 2023
This project will add a done button on your UITextField and UITextView

This project will add a done button on your UITextField and UITextView

Botla Venkatesh 0 Nov 23, 2021
A light-weight UITextView subclass that automatically grows and shrinks.

RSKGrowingTextView A light-weight UITextView subclass that automatically grows and shrinks based on the size of user input and can be constrained by m

Ruslan Skorb 939 Dec 21, 2022
UITextField and UITextView subclasses with placeholders that change into floating labels when the fields are populated with text.

Deprecated Please use JVFloatLabeledTextField instead or feel free to chime in on an issue if you'd like to take over the repo. RPFloatingPlaceholders

rob phillips 1.1k Jan 5, 2023
Animated UITextField and UITextView replacement for iOS

AnimatedTextInput iOS custom text input component used in the Jobandtalent app. Installation Use cocoapods to install this custom control in your proj

jobandtalent 757 Dec 15, 2022
ARAutocompleteTextView is a subclass of UITextView that automatically displays text suggestions in real-time

ARAutocompleteTextView is a subclass of UITextView that automatically displays text suggestions in real-time. This is perfect for automatically suggesting the domain as a user types an email address, #hashtag or @alexruperez.

Alex Rupérez 261 Jun 29, 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