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
📝 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 Jan 7, 2023
Growing text view in SwiftUI

Growing text view in SwiftUI If you are planning to write a messaging feature or you are just a SwiftUI enthusiast, this repository can be interesting

Maciej Gomółka 60 Jan 8, 2023
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
Dynamic textview with auto-resizing height & width that is also movable/draggable.

MarkupTextView Dynamic textview with auto-resizing height & width that is also movable/draggable. Requirements iOS 13 or above Installation MarkupText

Seok Kwun Park 2 Nov 17, 2022
An alternative to UIStackView for common Auto Layout patterns.

StackLayout StackLayout builds on Auto Layout to make some of the most common layouts easier to manage. It creates the constraints that you need and a

Bridger Maxwell 76 Jun 29, 2022
A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView and iPhone X safe area support for content reloading. Built for iOS 10 and later.

Arale A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView support for reloading your content. Built f

Putra Z. 43 Feb 4, 2022
MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding support for iPhone and additional opportunities to setup UIPresentationController size and feel form sheet.

MZFormSheetPresentationController MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding sup

Michał Zaborowski 979 Nov 17, 2022
Powerful and easy-to-use vector graphics Swift library with SVG support

Macaw Powerful and easy-to-use vector graphics Swift library with SVG support We are a development agency building phenomenal apps. What is Macaw? Mac

Exyte 5.9k Jan 1, 2023
🔍 Awesome fully customize search view like Pinterest written in Swift 5.0 + Realm support!

YNSearch + Realm Support Updates See CHANGELOG for details Intoduction ?? Awesome search view, written in Swift 5.0, appears search view like Pinteres

Kyle Yi 1.2k Dec 17, 2022
A UINavigationController subclass that support pop interactive UINavigationbar with hidden or show.

KDInteractiveNavigationController Features ✨ UINavigationController interactive with UINavigationBar hidden or show Hide all UINavigationController ba

Kingiol 154 Dec 3, 2022
SAHistoryNavigationViewController realizes iOS task manager like UI in UINavigationContoller. Support 3D Touch!

SAHistoryNavigationViewController Support 3D Touch for iOS9!! SAHistoryNavigationViewController realizes iOS task manager like UI in UINavigationConto

Taiki Suzuki 1.6k Dec 29, 2022
SheetPresentation for SwiftUI. Multiple devices support: iOS, watchOS, tvOS, macOS, macCatalyst.

SheetPresentation for SwiftUI. Multiple devices support: iOS, watchOS, tvOS, macOS, macCatalyst.

Aben 13 Nov 17, 2021
Fetch the star wars api from all the planets and list and show details using Swift UI and Combine

Star Wars Planets Fetch the star wars planet data by using stat war api, list and show details using SwiftUI and Combine frameworks ?? Swift UI Framew

null 1 Aug 10, 2022
🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0

Introduction ?? MediaBrowser can display one or more images or videos by providing either UIImage objects, PHAsset objects, or URLs to library assets,

Kyle Yi 631 Dec 29, 2022
Step-by-step progress view with labels and shapes. A good replacement for UIActivityIndicatorView and UIProgressView.

StepProgressView Step-by-step progress view with labels and shapes. A good replacement for UIActivityIndicatorView and UIProgressView. Usage let progr

Yonat Sharon 340 Dec 16, 2022
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

Haoking 336 Nov 26, 2022
UIPheonix is a super easy, flexible, dynamic and highly scalable UI framework + concept for building reusable component/control-driven apps for macOS, iOS and tvOS

UIPheonix is a super easy, flexible, dynamic and highly scalable UI framework + concept for building reusable component/control-driven apps for macOS, iOS and tvOS

Mohsan Khan 29 Sep 9, 2022
Simple and highly customizable iOS tag list view, in Swift.

TagListView Simple and highly customizable iOS tag list view, in Swift. Supports Storyboard, Auto Layout, and @IBDesignable. Usage The most convenient

Ela Workshop 2.5k Jan 5, 2023
Lightweight touch visualization library in Swift. A single line of code and visualize your touches!

TouchVisualizer is a lightweight pure Swift implementation for visualising touches on the screen. Features Works with just a single line of code! Supp

Morita Naoki 851 Dec 17, 2022