UITextView that starts scrolling when text reached N lines - ios

I'm start implementing text input to a chat app and wondering that is standard behavior of a UITextView with scroll enabled absolutely does not meet expectations.
I want just it is done in chats like WhatsApp. When text reached N, 5 for example lines, scroll bar appear and text container starts scrolling. I wrote code like this, but it doesn't work.
As i think needs to count rows in text container and make content insets, or something like this.
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = myTextView.frame.size.width
myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = myTextView.frame
let oldFrame = myTextView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
myTextView.frame = newFrame
let shift = oldFrame.height - newFrame.height
textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: shift, right: 0)
textView.scrollIndicatorInsets = textView.contentInset
textView.scrollRangeToVisible(textView.selectedRange)
}
And myTextView is specified as:
let myTextView : UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
textView.textContainer.maximumNumberOfLines = 5
textView.textContainer.lineBreakMode = .byWordWrapping
textView.inputAccessoryView = UIView()
return textView
}()

Not based on number of lines, but on a user defined height. You'll find your answer here:
https://stackoverflow.com/a/51235517/10115072

If you want this behaviour to happen is simple:
Create a UIView having UITextView inside
Create a height constraint in UIView priority 1000 of less than or equal your MAX_HEIGHT and also greater than or equal you MIN_HEIGHT
Create a height constraint in you TextView priority 999 equal to your MIN_HEIGHT
Then add this code to your controller
Code:
class YourViewController: KUIViewController {
#IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
textView.isScrollEnabled = true
}
}
extension YourViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let size = CGSize(width: view.frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
}
This has the same behaviour as WhatsApp textView

Related

How to adjust the height of the textview depends on the content in correct way?

I have tried 2 more methods. But those are not giving me the correct solution.
If i tried this one
func textViewDidChange(_ textView: UITextView) {
self.comments.translatesAutoresizingMaskIntoConstraints = true
self.comments.sizeToFit()
self.comments.isScrollEnabled = false
}
i can only type a one letter per a line.
If i tried this one
func textViewDidChange(_ textView: UITextView) {
self.comments.translatesAutoresizingMaskIntoConstraints = true
self.comments.isScrollEnabled = false
let fixedWidth = passedOut.frame.size.width
let newSize = comments.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
comments.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
}
Its working.
But at the viewDidLoad stage, the width of textview is certain less than which i constraints to the textview. But i gave the leading, trailing , height as same as passedOut textfield to that textview.
If i start typing in textview, the width of textview will become exact size which i want.
So pls suggest me what mistake i made?
Assign a height constraint to the text view
Use the following method to change the height:
func textViewDidChange(_ textView: UITextView) {
let size = textView.bounds.size
let newSize = textView.sizeThatFits(
CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude)
)
if size.height != newSize.height {
self.userMessageTextViewHeightConstraint.constant = newSize.height
textView.layoutIfNeeded()
}
}
You can achieve this behavior by doing 2 things in textview
Disable scrolling in textview
Assign the following constraints to textview
a) leading
b) trailing
c) top
d) height >= 30 ,assuming 30 is the minimum height of your textview.
Now when your text will grow textview will grow with it.

Auto-size view with dynamic font in enclosed textview

So here's one I just can't seem to find a matching case for in searching on here.
I have a small UIView that contains a UITextView, and the UIView needs to auto-size around the TextView for presentation over another view. Basically the TextView needs to fully fill the UIView, and the UIView should only be big enough to contain the TextView.
The TextView just contains a couple sentences that are meant to stay on the screen until an external thing happens, and certain values change.
Everything is great when I used a fixed-size font.
But hey... I'm an old guy, and I have the text size jacked up a bit on my phone. Testing it on my device shows where I must be missing something.
When using the dynamic font style "Title 2" in the textview properties, and turning on "Automatically adjust font" in the TextView properties, and having the text larger than the default, it seems as if I'm not properly capturing the size of the TextView's growth (with the bigger text) when creating the new bounding rect to toss at the frame. It's returning values that look a lot like the smaller, default-size text values rather than the increased text size.
Code is below, the view's class code as well as the calling code (made super explicit for posting here). I figure I'm either missing something silly like capturing the size after something happens to the fonts, but even moving this code to a new function and explicitly calling it after the controls fully draw doesn't seem to do it.
I hope this make sense.
Thanks, all.
Calling code:
let noWView:NoWitnessesYetView = (Bundle.main.loadNibNamed("NoWitnessesYetView", owner: nil, options: nil)!.first as! NoWitnessesYetView)
//if nil != noWView {
let leftGutter:CGFloat = 20.0
let bottomGutter:CGFloat = 24.0
let newWidth = self.view.frame.width - ( leftGutter + leftGutter )
let newTop = (eventMap.frame.minY + eventMap.frame.height) - ( noWView.frame.height + bottomGutter ) // I suspect here is the issue
// I suspect that loading without drawing is maybe not allowing
// the fonts to properly draw and the
// TextView to figure out the size...?
noWView.frame = CGRect(x: 20, y: newTop, width: newWidth, height: noWView.frame.height)
self.view.addSubview(noWView)
//}
Class code:
import UIKit
class NoWitnessesYetView: UIView {
#IBOutlet weak var textView: EyeneedRoundedTextView!
override func draw(_ rect: CGRect) {
let newWidth = self.frame.width
// form up a dummy size just to get the proper height for the popup
let workingSize:CGSize = self.textView.sizeThatFits(CGSize(width: newWidth, height: CGFloat(MAXFLOAT)))
// then build the real newSize value
let newSize = CGSize(width: newWidth, height: workingSize.height)
textView.frame.size = newSize
self.textView.isHidden = false
}
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clear // .blue
self.layer.cornerRadius = 10
}
}
This perfect way to do it the content comes from : https://www.youtube.com/watch?v=0Jb29c22xu8 .
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let's create our text view
let textView = UITextView()
textView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
textView.backgroundColor = .lightGray
textView.text = "Here is some default text that we want to show and it might be a couple of lines that are word wrapped"
view.addSubview(textView)
// use auto layout to set my textview frame...kinda
textView.translatesAutoresizingMaskIntoConstraints = false
[
textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
textView.heightAnchor.constraint(equalToConstant: 50)
].forEach{ $0.isActive = true }
textView.font = UIFont.preferredFont(forTextStyle: .headline)
textView.delegate = self
textView.isScrollEnabled = false
textViewDidChange(textView)
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
let size = CGSize(width: view.frame.width, height: .infinity)
let estimatedSize = textView.sizeThatFits(size)
textView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
}

UITextView: disable scrolling, multiline enable [duplicate]

As you can see in this image
the UITextView changes it's height according to the text length, I want to make it adjust it's height according to the text length.
*I saw other questions, but solutions there didn't work for me
this Works for me, all other solutions didn't.
func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}
In Swift 4 the syntax of arg.scrollEnabled = false has changed to arg.isScrollEnabled = false.
In Storyboard / Interface Builder simply disable scrolling in the Attribute inspector.
In code textField.scrollEnabled = false should do the trick.
All I had to do was:
Set the constraints to the top, left, and right of the textView.
Disable scrolling in Storyboard.
This allows autolayout to dynamically size the textView based on its content.
Give this a try:
CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;
Edit- Here's the Swift:
var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame
Swift 4
Add It To Your Class
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
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
}
Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding
swift 3
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
Swift 5, Use extension:
extension UITextView {
func adjustUITextViewHeight() {
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
Usecase:
textView.adjustUITextViewHeight()
And don't care about the height of texeView in the storyboard (just use a constant at first)
just make a connection with your textView's height Constraint
#IBOutlet var textView: UITextView!
#IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
and use this code below
textViewHeightConstraint.constant = self.textView.contentSize.height
If your textView is allowed to grow as tall as the content, then
textView.isScrollEnabled = false
should just work with autolayout.
If you want to remain the textView to be scrollable, you need to add an optional height constraint,
internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
constraint.priority = .defaultHigh
return constraint
}()
public override func layoutSubviews() {
super.layoutSubviews()
// Assuming there is width constraint setup on the textView.
let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}
The reason to override layoutSubviews() is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.
Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textView will be less than the contentSize. And the textView will be scrollable.
I added these two lines of code and work fine for me.
Works in Swift 5+
func adjustUITextViewHeight(textView : UITextView)
{
textView.translatesAutoresizingMaskIntoConstraints = true
textView.isScrollEnabled = false
textView.sizeToFit()
}
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
it's straight forward to do in programatic way. just follow these steps
add an observer to content length of textfield
[yourTextViewObject addObserver:self forKeyPath:#"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
implement observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
mTextViewHeightConstraint.constant = tv.contentSize.height;
[UIView animateWithDuration:0.2 animations:^{
[self.view layoutIfNeeded];
}];
}
if you want to stop textviewHeight to increase after some time during typing then implement this and set textview delegate to self.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if(range.length + range.location > textView.text.length)
{
return NO;
}
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > 100) ? NO : YES;
}
Swift 4+
This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView in your UITableViewCell.
Fit the textView to the contentView with constraints.
Disable scrolling for the textView.
Update the tableView on textViewDidChange.
That's all!
protocol TextViewUpdateProtocol {
func textViewChanged()
}
class TextViewCell: UITableViewCell {
//MARK: Reuse ID
static let identifier = debugDescription()
//MARK: UI Element(s)
/// Reference of the parent table view so that it can be updated
var textViewUpdateDelegate: TextViewUpdateProtocol!
lazy var textView: UITextView = {
let textView = UITextView()
textView.isScrollEnabled = false
textView.delegate = self
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
//MARK: Padding Variable(s)
let padding: CGFloat = 50
//MARK: Initializer(s)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubviews()
addConstraints()
textView.becomeFirstResponder()
}
//MARK: Helper Method(s)
func addSubviews() {
contentView.addSubview(textView)
}
func addConstraints() {
textView.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
textView.topAnchor .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
textView.bottomAnchor .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewUpdateDelegate.textViewChanged()
}
}
Now you have to inherit implement the protocol in your ViewController.
extension ViewController: TextViewUpdateProtocol {
func textViewChanged() {
tableView.beginUpdates()
tableView.endUpdates()
}
}
Check out my repo for the full implementation.
SWIFT 4
Change the size when typing
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
yourTextView.translatesAutoresizingMaskIntoConstraints = true
yourTextView.sizeToFit()
yourTextView.isScrollEnabled = false
let calHeight = yourTextView.frame.size.height
yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
}
Change the size when load
func textViewNotasChange(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.isScrollEnabled = false
let calHeight = arg.frame.size.height
arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
}
Call the function of the second option like this:
textViewNotasChange(arg: yourTextView)
In my project, the view controller is involved with lots of Constraints and StackView, and I set the TextView height as a constraint, and it varies based on the textView.contentSize.height value.
step1: get a IB outlet
#IBOutlet weak var textViewHeight: NSLayoutConstraint!
step2: use the delegation method below.
extension NewPostViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewHeight.constant = self.textView.contentSize.height + 10
}
}
Better yet swift 4 add as an extension:
extension UITextView {
func resizeForHeight(){
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
its working
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textviewconclusion.frame.size.width
textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textviewconclusion.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textviewconclusion.frame = newFrame
}
1 Add an observer to the content length of textfield
yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);
2 Implement observer
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let tv = object as! UITextView;
var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset.x = 0;
tv.contentOffset.y = -topCorrect;
self.yourTextView.contentSize.height = tv.contentSize.height;
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded();
});
}
Here are two pitfalls in iOS 8.3 when coming with textView.textContainer.maximumNumberOfLines = 10
Refer to my gist, please.
textView.attributedText = originalContent
let lineLimit = 10
textView.isEditable = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero // default is (8, 0, 8, 0)
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition
textView.textContainer.lineBreakMode = .byTruncatingTail
// two incomplete methods, which do NOT work in iOS 8.3
// size.width可能比maxSize.width小 ————遗憾的是 iOS 8.3 上此方法无视maximumNumberOfLines参数,所以得借助于UILabel
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines
// let size = textView.sizeThatFits(maxSize)
// 遗憾的是 iOS 8.3 上此方法失效了,得借助于UILabel
// Does not work in iOS 8.3
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size
// Suggested method: use a temperary label to get its size
let label = UILabel(); label.attributedText = originalContent
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size
textView.frame.size = size
Declaration here
fileprivate weak var textView: UITextView!
Call your setupview here
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
Setup here
fileprivate func setupViews() {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "your text here"
textView.font = UIFont.poppinsMedium(size: 14)
textView.textColor = UIColor.brownishGrey
textView.textAlignment = .left
textView.isEditable = false
textView.isScrollEnabled = false
textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
self.view.addSubview(textView)
self.textView = textView
setupConstraints()
}
Setup constraints here
fileprivate func setupConstraints() {
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
])
}
Whenever you need to resize the textview according to the inside content size, like in messageing app.
Use cocoapods(GrowingTextView), it will make your life easier, than coding the dynamic resizing of textview on your own.
Put textView in StackView
Set constraints(top, bottom, left, right) for stackView
Add height constraint to StackView, select this constraint and set it 'Greater Than or Equal' in Relation, on the right panel
if you want preload textView on controller load. Call this function from view didload():
func textViewDidChange(_ textView: UITextView) {
let esmitated = CGSize(width: txtView.frame.width, height: .infinity)
let esmitatedSize = txtView.sizeThatFits(esmitated)
self.heghtConstraint.constant = esmitatedSize.height
}

Adjusting height of UITextView to its text does not work properly

I wrote following code to fit UITextView's height to its text.
The size changes but top margin relative to first line of text differ every other time when I tap enter key on keyboard to add new line.
Setting
xCode 7.3
Deployment target: iOS 9
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
lazy var textView: UITextView = {
let tv = UITextView(frame: CGRectMake(20, 200, (self.view.frame.width - 40), 0) )
tv.backgroundColor = UIColor.lightGrayColor()
return tv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview( textView )
textView.delegate = self
let height = self.height(textView)
let frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.width, height)
textView.frame = frame
}
func textViewDidChange(textView: UITextView) {
let frame = CGRect(x: textView.frame.origin.x, y: textView.frame.origin.y, width: textView.frame.width, height: height(textView) )
textView.frame = frame
}
func height(textView: UITextView) -> CGFloat {
let size = CGSizeMake(textView.frame.size.width, CGFloat.max)
let height = textView.sizeThatFits(size).height
return height
}
}
I tried few other ways to fit UITextView height but they just acted the same say.
To fix this, subclass UITextView and override setContentOffset to allow scrolling only if the content height is larger than the intrinsic content height. Something like:
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
let allowScrolling = (contentSize.height > intrinsicContentSize.height)
if allowScrolling {
super.setContentOffset(contentOffset, animated: animated)
}
}
For auto-growing dynamic height text view, the caret moves on starting a new line. At this moment, the size of the text view hasn't grown to the new size yet. The text view tries to make the caret visible by scrolling the text content which is unnecessary.
You may also need to override intrinsicContentSize too.

how to make UITextView height dynamic according to text length?

As you can see in this image
the UITextView changes it's height according to the text length, I want to make it adjust it's height according to the text length.
*I saw other questions, but solutions there didn't work for me
this Works for me, all other solutions didn't.
func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}
In Swift 4 the syntax of arg.scrollEnabled = false has changed to arg.isScrollEnabled = false.
In Storyboard / Interface Builder simply disable scrolling in the Attribute inspector.
In code textField.scrollEnabled = false should do the trick.
All I had to do was:
Set the constraints to the top, left, and right of the textView.
Disable scrolling in Storyboard.
This allows autolayout to dynamically size the textView based on its content.
Give this a try:
CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;
Edit- Here's the Swift:
var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame
Swift 4
Add It To Your Class
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
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
}
Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding
swift 3
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
Swift 5, Use extension:
extension UITextView {
func adjustUITextViewHeight() {
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
Usecase:
textView.adjustUITextViewHeight()
And don't care about the height of texeView in the storyboard (just use a constant at first)
just make a connection with your textView's height Constraint
#IBOutlet var textView: UITextView!
#IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
and use this code below
textViewHeightConstraint.constant = self.textView.contentSize.height
If your textView is allowed to grow as tall as the content, then
textView.isScrollEnabled = false
should just work with autolayout.
If you want to remain the textView to be scrollable, you need to add an optional height constraint,
internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
constraint.priority = .defaultHigh
return constraint
}()
public override func layoutSubviews() {
super.layoutSubviews()
// Assuming there is width constraint setup on the textView.
let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}
The reason to override layoutSubviews() is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.
Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textView will be less than the contentSize. And the textView will be scrollable.
I added these two lines of code and work fine for me.
Works in Swift 5+
func adjustUITextViewHeight(textView : UITextView)
{
textView.translatesAutoresizingMaskIntoConstraints = true
textView.isScrollEnabled = false
textView.sizeToFit()
}
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
it's straight forward to do in programatic way. just follow these steps
add an observer to content length of textfield
[yourTextViewObject addObserver:self forKeyPath:#"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
implement observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
mTextViewHeightConstraint.constant = tv.contentSize.height;
[UIView animateWithDuration:0.2 animations:^{
[self.view layoutIfNeeded];
}];
}
if you want to stop textviewHeight to increase after some time during typing then implement this and set textview delegate to self.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if(range.length + range.location > textView.text.length)
{
return NO;
}
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > 100) ? NO : YES;
}
Swift 4+
This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView in your UITableViewCell.
Fit the textView to the contentView with constraints.
Disable scrolling for the textView.
Update the tableView on textViewDidChange.
That's all!
protocol TextViewUpdateProtocol {
func textViewChanged()
}
class TextViewCell: UITableViewCell {
//MARK: Reuse ID
static let identifier = debugDescription()
//MARK: UI Element(s)
/// Reference of the parent table view so that it can be updated
var textViewUpdateDelegate: TextViewUpdateProtocol!
lazy var textView: UITextView = {
let textView = UITextView()
textView.isScrollEnabled = false
textView.delegate = self
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
//MARK: Padding Variable(s)
let padding: CGFloat = 50
//MARK: Initializer(s)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubviews()
addConstraints()
textView.becomeFirstResponder()
}
//MARK: Helper Method(s)
func addSubviews() {
contentView.addSubview(textView)
}
func addConstraints() {
textView.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
textView.topAnchor .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
textView.bottomAnchor .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewUpdateDelegate.textViewChanged()
}
}
Now you have to inherit implement the protocol in your ViewController.
extension ViewController: TextViewUpdateProtocol {
func textViewChanged() {
tableView.beginUpdates()
tableView.endUpdates()
}
}
Check out my repo for the full implementation.
SWIFT 4
Change the size when typing
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
yourTextView.translatesAutoresizingMaskIntoConstraints = true
yourTextView.sizeToFit()
yourTextView.isScrollEnabled = false
let calHeight = yourTextView.frame.size.height
yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
}
Change the size when load
func textViewNotasChange(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.isScrollEnabled = false
let calHeight = arg.frame.size.height
arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
}
Call the function of the second option like this:
textViewNotasChange(arg: yourTextView)
In my project, the view controller is involved with lots of Constraints and StackView, and I set the TextView height as a constraint, and it varies based on the textView.contentSize.height value.
step1: get a IB outlet
#IBOutlet weak var textViewHeight: NSLayoutConstraint!
step2: use the delegation method below.
extension NewPostViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewHeight.constant = self.textView.contentSize.height + 10
}
}
Better yet swift 4 add as an extension:
extension UITextView {
func resizeForHeight(){
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
its working
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textviewconclusion.frame.size.width
textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textviewconclusion.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textviewconclusion.frame = newFrame
}
1 Add an observer to the content length of textfield
yourTextView.addObserver(self, forKeyPath: "contentSize", options: (NSKeyValueObservingOptions.new), context: nil);
2 Implement observer
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let tv = object as! UITextView;
var topCorrect = (tv.bounds.size.height - tv.contentSize.height * tv.zoomScale)/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset.x = 0;
tv.contentOffset.y = -topCorrect;
self.yourTextView.contentSize.height = tv.contentSize.height;
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded();
});
}
Here are two pitfalls in iOS 8.3 when coming with textView.textContainer.maximumNumberOfLines = 10
Refer to my gist, please.
textView.attributedText = originalContent
let lineLimit = 10
textView.isEditable = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero // default is (8, 0, 8, 0)
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition
textView.textContainer.lineBreakMode = .byTruncatingTail
// two incomplete methods, which do NOT work in iOS 8.3
// size.width可能比maxSize.width小 ————遗憾的是 iOS 8.3 上此方法无视maximumNumberOfLines参数,所以得借助于UILabel
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines
// let size = textView.sizeThatFits(maxSize)
// 遗憾的是 iOS 8.3 上此方法失效了,得借助于UILabel
// Does not work in iOS 8.3
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size
// Suggested method: use a temperary label to get its size
let label = UILabel(); label.attributedText = originalContent
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size
textView.frame.size = size
Declaration here
fileprivate weak var textView: UITextView!
Call your setupview here
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
Setup here
fileprivate func setupViews() {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "your text here"
textView.font = UIFont.poppinsMedium(size: 14)
textView.textColor = UIColor.brownishGrey
textView.textAlignment = .left
textView.isEditable = false
textView.isScrollEnabled = false
textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
self.view.addSubview(textView)
self.textView = textView
setupConstraints()
}
Setup constraints here
fileprivate func setupConstraints() {
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
])
}
Whenever you need to resize the textview according to the inside content size, like in messageing app.
Use cocoapods(GrowingTextView), it will make your life easier, than coding the dynamic resizing of textview on your own.
Put textView in StackView
Set constraints(top, bottom, left, right) for stackView
Add height constraint to StackView, select this constraint and set it 'Greater Than or Equal' in Relation, on the right panel
if you want preload textView on controller load. Call this function from view didload():
func textViewDidChange(_ textView: UITextView) {
let esmitated = CGSize(width: txtView.frame.width, height: .infinity)
let esmitatedSize = txtView.sizeThatFits(esmitated)
self.heghtConstraint.constant = esmitatedSize.height
}

Resources