Changing the frame of an inputAccessoryView in iOS 8 - ios

Long time lurker - first time poster!
I am having an issue while recreating a bar with a UITextView like WhatsApp does it.
I am using a custom UIView subclass, and lazily instantiating it on:
- (UIView *)inputAccessoryView
and returning YES on:
- (BOOL)canBecomeFirstResponder
Now, I want to change the size of the inputAccessoryView when the UITextView grows in size. On iOS 7, I would simply change the size of the frame of said view - and not it's origin -, and then call reloadInputViews and it would work: the view would be moved upwards so that it is fully visible above the keyboard.
On iOS 8, however, this does not work. The only way to make it work is to also change the origin of the frame to a negative value. This would be fine, except it creates some weird bugs: for example, the UIView returns to the 'original' frame when entering any text.
Is there something I am missing? I am pretty certain WhatsApp uses inputAccessoryView because of the way they dismiss the keyboard on drag - only in the latest version of the app.
Please let me know if you can help me out! Or if there is any test you would like me to run!
Thank you! :)
BTW, here is the code I am using to update the height of the custom UIView called composeBar:
// ComposeBar frame size
CGRect frame = self.composeBar.frame;
frame.size.height += heightDifference;
frame.origin.y -= heightDifference;
self.composeBar.frame = frame;
[self.composeBar.textView reloadInputViews]; // Tried with this
[self reloadInputViews]; // and this
Edit: full source code is available # https://github.com/manuelmenzella/SocketChat-iOS

I've been banging my head against the wall on this one for quite some time, as the behavior changed from iOS 7 to iOS 8. I tried everything, until the most obvious solution of all worked for me:
inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
duh!

To sum up JohnnyC's answer: set your inpitAccessoryView's autoresizingMask to .flexibleHeight, calculate its intrinsicContentSize and let the framework do the rest.
Full code, updated for Swift 3:
class InputAccessoryView: UIView, UITextViewDelegate {
let textView = UITextView()
override var intrinsicContentSize: CGSize {
// Calculate intrinsicContentSize that will fit all the text
let textSize = textView.sizeThatFits(CGSize(width: textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
return CGSize(width: bounds.width, height: textSize.height)
}
override init(frame: CGRect) {
super.init(frame: frame)
// This is required to make the view grow vertically
autoresizingMask = .flexibleHeight
// Setup textView as needed
addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": textView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": textView]))
textView.delegate = self
// Disabling textView scrolling prevents some undesired effects,
// like incorrect contentOffset when adding new line,
// and makes the textView behave similar to Apple's Messages app
textView.isScrollEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
// Re-calculate intrinsicContentSize when text changes
invalidateIntrinsicContentSize()
}
}

The issue is that in iOS 8, an NSLayoutConstraint that sets the inputAccessoryView's height equal to its initial frame height is installed automatically. In order to fix the layout problem, you need to update that constraint to the desired height and then instruct your inputAccessoryView to lay itself out.
- (void)changeInputAccessoryView:(UIView *)inputAccessoryView toHeight:(CGFloat)height {
for (NSLayoutConstraint *constraint in [inputAccessoryView constraints]) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
constraint.constant = height;
[inputAccessoryView layoutIfNeeded];
break;
}
}
}

Here's a complete, self-contained solution (thanks #JohnnyC and #JoãoNunes for pointing me in the right direction, #stigi for explaining how to animate intrinsicContent changes):
class InputAccessoryView: UIView {
// InputAccessoryView is instantiated from nib, but it's not a requirement
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .FlexibleHeight
}
override func intrinsicContentSize() -> CGSize {
let exactHeight = // calculate exact height of your view here
return CGSize(width: UIViewNoIntrinsicMetric, height: exactHeight)
}
func somethingDidHappen() {
// invalidate intrinsic content size, animate superview layout
UIView.animateWithDuration(0.2) {
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}
}

100% working and very simple solution is to enumerate all constraints and set new height value. Here is some C# code (xamarin):
foreach (var constraint in inputAccessoryView.Constraints)
{
if (constraint.FirstAttribute == NSLayoutAttribute.Height)
{
constraint.Constant = newHeight;
}
}

Unfortunately, iOS8 adds a private height constraint to the inputAccessoryView, and this constraint is not public.
I recommend recreating the accessory view when its frame should change, and call reloadInputViews so that the new one is installed.
This is what I do, and it works as expected.

Yep, iOS8 adds a private height constraint to the inputAccessoryView.
Taking into account that recreating whole inputAccessoryView and replace old one is can be really expensive operation, you can just remove constraints before reload input views
[inputAccessoryView removeConstraints:[inputAccessoryView constraints]];
[textView reloadInputViews];
Just another workaround

To fix this I used inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
But of course this caused my textview to collapse.
So adding a constraint to the toolbar and updating it when I have to, or adding the constraint to the textview itself and update it worked for me.

frist, get inputAccessoryView and set nil
UIView *inputAccessoryView = yourTextView.inputAccessoryView;
yourTextView.inputAccessoryView = nil;
[yourTextView reloadInputViews];
then set frame and layout
inputAccessoryView.frame = XXX
[inputAccessoryView setNeedsLayout];
[inputAccessoryView layoutIfNeeded];
last set new inputAccessoryView again and reload
yourTextView.inputAccessoryView = inputAccessoryView;
[yourTextView reloadInputViews];

Related

how can i increase the height of an inputAccessoryView

I have spent several days on this with no solution in sight.
I have an inputAccessoryView which consists of a UIView containing a textView and two buttons. The behaviour of the inputAccessoryView is as expected and works fine in all cases except one.
When the height of the textView increases, I am trying to increase the height of the inputAccessoryView by the same amount. When I redefine the height of the inputAccessoryView in textViewDidChange, the inputAccessoryView increases height downwards over the keyboard instead of upwards.
I have tried many different suggestions from SO but nothing has worked. I guess it is the automatically added NSLayoutConstraint of the inputAccessoryView but I have no idea how to change that value in swift and iOS 8.3.
func textViewDidChange(textView: UITextView) {
var contentSize = messageTextView.sizeThatFits(CGSizeMake(messageTextView.frame.size.width, CGFloat.max))
inputAccessoryView.frame.size.height = contentSize.height + 16
}
adding
inputAccessoryView.setTranslatesAutoresizingMaskIntoConstraints(true)
to the above code helps and the inputAccessoryView height increases upwards correctly however I get Unable to simultaneously satisfy constraints for several constraints and it is very difficult to identify the offenders. Also I get an odd effect of the textView creating extra space below on every second instance of a new line.
thanks.
To make input accessory view grow vertically you just set its autoresizingMask = .flexibleHeight, calculate its intrinsicContentSize and let the framework do the rest.
The code:
class InputAccessoryView: UIView, UITextViewDelegate {
let textView = UITextView()
override init(frame: CGRect) {
super.init(frame: frame)
// This is required to make the view grow vertically
self.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
// Setup textView as needed
self.addSubview(self.textView)
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.textView.delegate = self
// Disabling textView scrolling prevents some undesired effects,
// like incorrect contentOffset when adding new line,
// and makes the textView behave similar to Apple's Messages app
self.textView.isScrollEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
// Calculate intrinsicContentSize that will fit all the text
let textSize = self.textView.sizeThatFits(CGSize(width: self.textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
return CGSize(width: self.bounds.width, height: textSize.height)
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
// Re-calculate intrinsicContentSize when text changes
self.invalidateIntrinsicContentSize()
}
}
Fast forward to 2020, you can just do the following, everything else the same as in maxkonovalov's answer
override var intrinsicContentSize: CGSize {
return .zero
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
sizeToFit()
}

UITableViewWrapperView and UITableView size differs with autolayout

I am building a chat. Everything seem to be quite ok but I bumped into sort of 'buggy' problem.
i got UIViewController with UITextView bar for entering message and UITableView.
They are in this constraint: "V:|-(64)-[chatTable][sendMessageBar]-(keyboard)-|".
When the keyboard is not out - the constant of this constraint is 0. and after keyboard is out - i increase the constant to keyboard height.
when the keyboard is not out:
self.table.contentSize = (375.0,78.5)
self.table.bounds = (0.0,-490.0,375.0,568.5)
self.table.frame = (0.0,64.0,375.0,568.5)
self.table.subviews[0].frame (UITableViewWrapperView) = (0.0,0.0,375.0,568.5)
self.table.subviews[0].frame (UITableViewWrapperView) = (0.0,0.0,375.0,568.5)
and when the keyboard comes out:
self.table.contentSize = (375.0,78.5)
self.table.bounds = (0.0,-274.0,375.0,352.5
self.table.frame = (0.0,64.0,375.0,352.5)
self.table.subviews[0].frame (UITableViewWrapperView) = (0.0,-137.5,375.0,137.5)
self.table.subviews[0].frame (UITableViewWrapperView) = (0.0,0.0,375.0,137.5)
So the UITableViewWrapperView, after I increase constraints constant, differs in size to its superview - UITableView. Is there a way to fix this ? I would assume that UITableViewWrapperView would change its frame and bounds according to UITableView but it does not.
Any ideas where is the problem or how could I work around it ?
ADDING:
After some more research - it seems that it happens somewhere between viewWillLayoutSubviews and viewDidLayoutSubviews. It is kinda weird tho:
override func viewWillLayoutSubviews() {
println("WrapperView Frame :991: \(self.table.subviews[0].frame)") \\ WrapperView Frame :991: (0.0,0.0,375.0,568.5)
super.viewWillLayoutSubviews()
println("WrapperView Frame :992: \(self.table.subviews[0].frame)") \\ WrapperView Frame :992: (0.0,0.0,375.0,568.5)
}
override func viewDidLayoutSubviews() {
println("WrapperView Frame :6: \(self.table.subviews[0].frame)") \\ WrapperView Frame :6: (0.0,-137.5,375.0,137.5)
super.viewDidLayoutSubviews()
println(">> viewDidLayoutSubviews")
}
So it seems that something happens there that messes up the UITableViewWrapperView
The following fixed it for me:
func fixTableViewInsets() {
let zContentInsets = UIEdgeInsetsZero
tableView.contentInset = zContentInsets
tableView.scrollIndicatorInsets = zContentInsets
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
fixTableViewInsets()
}
I discovered that at viewWillAppear() that the insets were all 0. But at viewDidAppear(), they had been modified to apparently offset for navigation bar, etc. This makes the UITableViewWrapperView different from the UITableView.
I changed the insets in its own routine so that it was easier to experiment with calling it from different places. The viewWillLayoutSubviews() let it get changed before being presented - placing the change in viewDidAppear() caused the table to jerk.
I ran into this today and while the fix suggested by #anorskdev works nicely, it seems that the root cause of the issue is the automaticallyAdjustsScrollViewInsets property of UIViewController, which is true by default. I turned it off in my storyboard and the problem went away. Look for the "Adjust Scroll View Insets" checkbox in the View Controller inspector and make sure it's unchecked.
It seems that it is a bug (fighting with this bug took all day for me)
Finally this workaround helped:
for (UIView *subview in tableView.subviews)
{
if ([NSStringFromClass([subview class]) isEqualToString:#"UITableViewWrapperView"])
{
subview.frame = CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height);
}
}
After small investigation I have found this solution with setting all the safeAreaInsets and layoutMargins on the UITableView to zero:
Swift 4 snipset:
class CustomTableView: UITableView {
override var safeAreaInsets: UIEdgeInsets {
get {
return .zero
}
}
override var layoutMargins: UIEdgeInsets {
get {
return .zero
}
set {
super.layoutMargins = .zero
}
}
}
The main problem is safeAreaInsets introduced in tvOS 11.0 - the UITableViewWrapperView just took the properties from the parent view (UITableView) and renders the content with safeAreaInsets.
I was facing the same issue on tvOS 11.3, and neither of suggestions related with zero insets or scroll disable did the job, except looping through tableView's subviews and setting the UITableViewWrapperView's frame to the tableView's frame.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
for view in tableView.subviews {
if String(describing: type(of: view)) == "UITableViewWrapperView" {
view.frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height)
}
}
}
In iOS 11 UITableViewWrapperView has gone, so this problem may occur only on later iOS versions. I faced it on iOS10 when I pushed custom UIViewController in UINavigationController stack.
So, the solution is to override property automaticallyAdjustsScrollViewInsets in custom view controller like this:
override var automaticallyAdjustsScrollViewInsets: Bool {
get {
return false
}
set {
}
}
Objective C version of this answer given by anorskdev
- (void) viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[tableView setContentInset:UIEdgeInsetsZero];
[tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}
edit: Turning off automaticallyAdjustsScrollViewInsets on the hosting ViewController, as suggested by Steve Roy in this answer, also worked and is the one I went with, as it seems cleaner to disable the behaviour rather than correcting it afterwards.

iOS Keyboard - input Accessory View xib with autolayout not receiving touch event

I've built a growing UITextView attached to the keyboard, similar to the stock Messages app, by loading a .xib into the keyboard's inputAccessoryView as such:
self.keyboardAccessoryView = [[[NSBundle mainBundle]
loadNibNamed:#"KeyboardAccessoryView"
owner:self options:nil]
firstObject];
The .xib looks like this, and is using layout constraints so that the textView grows vertically when the user enters more lines of text:
This is all working great, with rotation and everything, except one big bug -- when the text is multiple lines, only the very bottom line handles touch events. This means that a user cannot scroll inside the UITextView because their touch events are being passed to the (dark gray) view in the back and scrolling that instead. They also cannot select and edit their text on the top 3 lines.
I think I could do a workaround by capturing the coordinates of all tap events and checking if the keyboard is open and how tall the UITextView is, then selecting the correct element to receive the touch event. But this is brittle solution that is more complicated with rotation. Is there something I'm missing in my auto-growing text view approach, or some easier fix?
To make input accessory view grow vertically you just set its autoresizingMask = .flexibleHeight, calculate its intrinsicContentSize and let the framework do the rest.
The code:
class InputAccessoryView: UIView, UITextViewDelegate {
let textView = UITextView()
override init(frame: CGRect) {
super.init(frame: frame)
// This is required to make the view grow vertically
self.autoresizingMask = UIViewAutoresizing.flexibleHeight
// Setup textView as needed
self.addSubview(self.textView)
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.textView.delegate = self
// Disabling textView scrolling prevents some undesired effects,
// like incorrect contentOffset when adding new line,
// and makes the textView behave similar to Apple's Messages app
self.textView.scrollEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
// Calculate intrinsicContentSize that will fit all the text
let textSize = self.textView.sizeThatFits(CGSize(width: self.textView.bounds.width, height: CGFloat.max))
return CGSize(width: self.bounds.width, height: textSize.height)
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
// Re-calculate intrinsicContentSize when text changes
self.invalidateIntrinsicContentSize()
}
}
This approach is quite straightforward and reliable, as it doesn't require hacking constraints or recreating the view each time its size changes.
I figured out that even though the keyboard accessory input grows vertically with auto layout, its frame does not. So you have to adjust the keyboard accessory's frame each time the height of the uitextview grows, shrinks, and rotates. This introduces some complications as UITextView's in iOS7 are notoriously buggy -- I noticed behavior was not consistent across iPhone, iPad, and the Simulator.

UICollectionView autosize height

How do I properly resize a UICollectionView so that it fully displays its contents? I have tried many things, including setting its frame, calling reloadData and invalidating the layout:
self.collectionView.contentSize = CGSizeMake(300, 2000);
self.collectionView.frame = CGRectMake(0, 0, 300, 2000);
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
but none of this has any effect. After pressing the button I still see the initial view, like this:
I have a small demo program where I have a data source producing 100 elements. In Interface Builder I initially set the size of the UICollectionView to a small value so that not all elements fit, after that I press a button after which the code above is executed. I expect the UICollectionView to now show all elements, but it doesn't.
EDIT: The demo program can be found at https://github.com/mjdemilliano/TestUICollectionView.
EDIT2: I have observed that the frame update is lost at some point, because if I press the button again, the current frame is back to the old value. After adding some log statements in the button event handler, the log output is:
before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}
before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}
I don't understand why the frame change is not kept, what is changing it.
At some point I will replace the hardcoded values by values obtained from the flow layout, but I wanted to rule that out and keep my example as simple as possible.
Context: What I want to do eventually is the following: I have a scrollable view with various controls like labels and images, and a collection view with dynamic content. I want to scroll all that, not just the collection view, therefore I am not using the collection view's own scrolling facilities, which work fine.
I solved this eventually by fixing all Auto Layout issues, fixing the height of the collection view using a constraint. Then, whenever I know the content has changed I update the value of the constraint using the value collectionView.contentSize.height:
self.verticalLayoutConstraint.constant = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
Then the collection view is resized properly and it behaves nicely within the overall scrollview. I have updated the GitHub test project with my changes.
To me, doing this by updating the constraint manually instead of being able to tell iOS: "make the frame height of the collection view as large as needed" does not feel right to me, but it's the best I have come up with so far. Please post a better answer if you have one.
It seems to work nicely with a custom UICollectionView class.
class AutoSizedCollectionView: UICollectionView {
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
Set your custom class in the interface builder:
This way you can also set your collection views intrinsic size to 'placeholder' in interface builder to avoid having to set a height constraint.
I hope this helps someone else.
Here's my implementation in Swift 3:
override func sizeThatFits(_ size: CGSize) -> CGSize {
if (self.superview != nil) {
self.superview?.layoutIfNeeded()
}
return collectionView.contentSize
}
UICollectionViewFlowLayout *flowLayout;
flowLayout = [[UICollectionViewFlowLayout alloc]init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[flowLayout setMinimumInteritemSpacing:0.0f];
[flowLayout setMinimumLineSpacing:0.0f];
[self.collectionView setPagingEnabled:NO];
[flowLayout setItemSize:CGSizeMake(322.0, 148.0)]; //important to leave no white space between the images
[self.collectionView setCollectionViewLayout:flowLayout];
I found that autolayout in the storyboard is not helping too much. A correct setting for the UICollectionViewFlowLayout for your collectionView is the real help. If you adjust item size with setItemSize, you may get the result you want.
The simplest method I found is to override sizeThatFits: methods as is:
- (CGSize)sizeThatFits:(CGSize)size
{
if( self.superview )
[self.superview layoutIfNeeded]; // to force evaluate the real layout
return self.collectionViewLayout.collectionViewContentSize;
}
Here's a way to bind the CollectionView's height via it's intrinsic size.
I used it to properly size a CollectionView inside a TableView Cell (with dynamic cells height). and it works perfectly.
First, add this to your UICollectionView subclass:
override var intrinsicContentSize: CGSize {
get {
return self.contentSize
}
}
Then call layoutIfNeeded() after you reload data:
reloadData()
layoutIfNeeded()
You can try out my custom AGCollectionView class
Assign a height constraint of collectionView using a storyboard or programmatically.
- Assign this class to your UICollectionView.
class AGCollectionView: UICollectionView {
fileprivate var heightConstraint: NSLayoutConstraint!
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.associateConstraints()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.associateConstraints()
}
override open func layoutSubviews() {
super.layoutSubviews()
if self.heightConstraint != nil {
self.heightConstraint.constant = floor(self.contentSize.height)
}
else{
self.sizeToFit()
print("Set a heightConstraint set size to fit content")
}
}
func associateConstraints() {
// iterate through height constraints and identify
for constraint: NSLayoutConstraint in constraints {
if constraint.firstAttribute == .height {
if constraint.relation == .equal {
heightConstraint = constraint
}
}
}
}
}
Add IBOutlet for CollectionView Height Constraint
--> Like #IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
Add Below snipped code.
For me it is even simpler I think
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//add following code line after adding cells, before Return
...........
.........
scrollView.contentSize = = collectionView.contentSize;
//now scrollView size is equal to collectionView size. No matter how small or big it is.
return cell;
}

UITextView that expands to text using auto layout

I have a view that is laid out completely using auto layout programmatically. I have a UITextView in the middle of the view with items above and below it. Everything works fine, but I want to be able to expand UITextView as text is added. This should push everything below it down as it expands.
I know how to do this the "springs and struts" way, but is there an auto layout way of doing this? The only way I can think of is by removing and re-adding the constraint every time it needs to grow.
Summary: Disable scrolling of your text view, and don't constraint its height.
To do this programmatically, put the following code in viewDidLoad:
let textView = UITextView(frame: .zero, textContainer: nil)
textView.backgroundColor = .yellow // visual debugging
textView.isScrollEnabled = false // causes expanding height
view.addSubview(textView)
// Auto Layout
textView.translatesAutoresizingMaskIntoConstraints = false
let safeArea = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeArea.topAnchor),
textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor)
])
To do this in Interface Builder, select the text view, uncheck Scrolling Enabled in the Attributes Inspector, and add the constraints manually.
Note: If you have other view/s above/below your text view, consider using a UIStackView to arrange them all.
Here's a solution for people who prefer to do it all by auto layout:
In Size Inspector:
Set content compression resistance priority vertical to 1000.
Lower the priority of constraint height by click "Edit" in Constraints. Just make it less than 1000.
In Attributes Inspector:
Uncheck "Scrolling Enabled"
UITextView doesn't provide an intrinsicContentSize, so you need to subclass it and provide one. To make it grow automatically, invalidate the intrinsicContentSize in layoutSubviews. If you use anything other than the default contentInset (which I do not recommend), you may need to adjust the intrinsicContentSize calculation.
#interface AutoTextView : UITextView
#end
#import "AutoTextView.h"
#implementation AutoTextView
- (void) layoutSubviews
{
[super layoutSubviews];
if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
[self invalidateIntrinsicContentSize];
}
}
- (CGSize)intrinsicContentSize
{
CGSize intrinsicContentSize = self.contentSize;
// iOS 7.0+
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;
intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;
}
return intrinsicContentSize;
}
#end
The view containing UITextView will be assigned its size with setBounds by AutoLayout. So, this is what I did. The superview is initially set up all the other constraints as they should be, and in the end I put one special constraint for UITextView's height, and I saved it in an instance variable.
_descriptionHeightConstraint = [NSLayoutConstraint constraintWithItem:_descriptionTextView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.f
constant:100];
[self addConstraint:_descriptionHeightConstraint];
In the setBounds method, I then changed the value of the constant.
-(void) setBounds:(CGRect)bounds
{
[super setBounds:bounds];
_descriptionTextView.frame = bounds;
CGSize descriptionSize = _descriptionTextView.contentSize;
[_descriptionHeightConstraint setConstant:descriptionSize.height];
[self layoutIfNeeded];
}
You can do it through storyboard, just disable "Scrolling Enabled":)
I've found it's not entirely uncommon in situations where you may still need isScrollEnabled set to true to allow a reasonable UI interaction. A simple case for this is when you want to allow an auto expanding text view but still limit it's maximum height to something reasonable in a UITableView.
Here's a subclass of UITextView I've come up with that allows auto expansion with auto layout but that you could still constrain to a maximum height and which will manage whether the view is scrollable depending on the height. By default the view will expand indefinitely if you have your constraints setup that way.
import UIKit
class FlexibleTextView: UITextView {
// limit the height of expansion per intrinsicContentSize
var maxHeight: CGFloat = 0.0
private let placeholderTextView: UITextView = {
let tv = UITextView()
tv.translatesAutoresizingMaskIntoConstraints = false
tv.backgroundColor = .clear
tv.isScrollEnabled = false
tv.textColor = .disabledTextColor
tv.isUserInteractionEnabled = false
return tv
}()
var placeholder: String? {
get {
return placeholderTextView.text
}
set {
placeholderTextView.text = newValue
}
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
isScrollEnabled = false
autoresizingMask = [.flexibleWidth, .flexibleHeight]
NotificationCenter.default.addObserver(self, selector: #selector(UITextInputDelegate.textDidChange(_:)), name: Notification.Name.UITextViewTextDidChange, object: self)
placeholderTextView.font = font
addSubview(placeholderTextView)
NSLayoutConstraint.activate([
placeholderTextView.leadingAnchor.constraint(equalTo: leadingAnchor),
placeholderTextView.trailingAnchor.constraint(equalTo: trailingAnchor),
placeholderTextView.topAnchor.constraint(equalTo: topAnchor),
placeholderTextView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var text: String! {
didSet {
invalidateIntrinsicContentSize()
placeholderTextView.isHidden = !text.isEmpty
}
}
override var font: UIFont? {
didSet {
placeholderTextView.font = font
invalidateIntrinsicContentSize()
}
}
override var contentInset: UIEdgeInsets {
didSet {
placeholderTextView.contentInset = contentInset
}
}
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
if size.height == UIViewNoIntrinsicMetric {
// force layout
layoutManager.glyphRange(for: textContainer)
size.height = layoutManager.usedRect(for: textContainer).height + textContainerInset.top + textContainerInset.bottom
}
if maxHeight > 0.0 && size.height > maxHeight {
size.height = maxHeight
if !isScrollEnabled {
isScrollEnabled = true
}
} else if isScrollEnabled {
isScrollEnabled = false
}
return size
}
#objc private func textDidChange(_ note: Notification) {
// needed incase isScrollEnabled is set to true which stops automatically calling invalidateIntrinsicContentSize()
invalidateIntrinsicContentSize()
placeholderTextView.isHidden = !text.isEmpty
}
}
As a bonus there's support for including placeholder text similar to UILabel.
I see multiple answers suggest simply turning off scrollEnabled. This is the best solution. I’m writing this answer to explain why it works.
UITextView implements the intrinsicContentSize property only if scrollEnabled == NO. The disassembly of the getter method looks like this:
- (CGSize)intrinsicContentSize {
if (self.scrollEnabled) {
return CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric);
} else {
// Calculate and return intrinsic content size based on current width.
}
}
That means you just need to make sure the width of the text view is constrained enough and then you can make use of the intrinsic content height, either via Auto Layout content hugging/compression resistance priorities or directly using the value during manual layout.
Unfortunately, this behavior is not documented. Apple could have easily saved us all some headaches… no need for an extra height constraint, subclassing, etc.
You can also do it without subclassing UITextView. Have a look at my answer to How do I size a UITextView to its content on iOS 7?
Use the value of this expression:
[textView sizeThatFits:CGSizeMake(textView.frame.size.width, CGFLOAT_MAX)].height
to update the constant of the textView's height UILayoutConstraint.
This more of a very important comment
Key to understanding why vitaminwater's answer works are three things:
Know that UITextView is a subclass of UIScrollView class
Understand how ScrollView works and how its contentSize is calculated. For more see this here answer and its various solutions and comments.
Understand what contentSize is and how its calculated. See here and here. It might also help that setting contentOffset is likely nothing but:
func setContentOffset(offset: CGPoint)
{
CGRect bounds = self.bounds
bounds.origin = offset
self.bounds = bounds
}
For more see objc scrollview and understanding scrollview
Combining the three together you'd easily understand that you need allow the the textView's intrinsic contentSize to work along AutoLayout constraints of the textView to drive the logic. It's almost as if you're textView is functioning like a UILabel
To make that happen you need to disable scrolling which basically means the scrollView's size, the contentSize's size and in case of adding a containerView, then the containerView's size would all be the same. When they're the same you have NO scrolling. And you'd have 0 contentOffset. Having 0 contentOffSet means you've not scrolled down. Not even a 1 point down! As a result the textView will be all stretched out.
It's also worth nothing that 0 contentOffset means that the scrollView's bounds and frame are identical.
If you scroll down 5 points then your contentOffset would be 5, while your scrollView.bounds.origin.y - scrollView.frame.origin.y would be equal to 5
I needed a text view that would automatically grow up until a certain maximum height, then become scrollable. Michael Link's answer worked great but I wanted to see if I could come up with something a bit simpler. Here's what I came up with:
Swift 5.3, Xcode 12
class AutoExpandingTextView: UITextView {
private var heightConstraint: NSLayoutConstraint!
var maxHeight: CGFloat = 100 {
didSet {
heightConstraint?.constant = maxHeight
}
}
private var observer: NSObjectProtocol?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
heightConstraint = heightAnchor.constraint(equalToConstant: maxHeight)
observer = NotificationCenter.default.addObserver(forName: UITextView.textDidChangeNotification, object: nil, queue: .main) { [weak self] _ in
guard let self = self else { return }
self.heightConstraint.isActive = self.contentSize.height > self.maxHeight
self.isScrollEnabled = self.contentSize.height > self.maxHeight
self.invalidateIntrinsicContentSize()
}
}
}
An important thing to note:
Since UITextView is a subclass of UIScrollView, it is subject to the automaticallyAdjustsScrollViewInsets property of UIViewController.
If you are setting up the layout and the TextView is the the first subview in a UIViewControllers hierarchy, it will have its contentInsets modified if automaticallyAdjustsScrollViewInsets is true sometimes causing unexpected behaviour in auto layout.
So if you're having problems with auto layout and text views, try setting automaticallyAdjustsScrollViewInsets = false on the view controller or moving the textView forward in the hierarchy.
Plug and Play Solution - Xcode 9
Autolayout just like UILabel, with the link detection, text selection, editing and scrolling of UITextView.
Automatically handles
Safe area
Content insets
Line fragment padding
Text container insets
Constraints
Stack views
Attributed strings
Whatever.
A lot of these answers got me 90% there, but none were fool-proof.
Drop in this UITextView subclass and you're good.
#pragma mark - Init
- (instancetype)initWithFrame:(CGRect)frame textContainer:(nullable NSTextContainer *)textContainer
{
self = [super initWithFrame:frame textContainer:textContainer];
if (self) {
[self commonInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self commonInit];
}
return self;
}
- (void)commonInit
{
// Try to use max width, like UILabel
[self setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
// Optional -- Enable / disable scroll & edit ability
self.editable = YES;
self.scrollEnabled = YES;
// Optional -- match padding of UILabel
self.textContainer.lineFragmentPadding = 0.0;
self.textContainerInset = UIEdgeInsetsZero;
// Optional -- for selecting text and links
self.selectable = YES;
self.dataDetectorTypes = UIDataDetectorTypeLink | UIDataDetectorTypePhoneNumber | UIDataDetectorTypeAddress;
}
#pragma mark - Layout
- (CGFloat)widthPadding
{
CGFloat extraWidth = self.textContainer.lineFragmentPadding * 2.0;
extraWidth += self.textContainerInset.left + self.textContainerInset.right;
if (#available(iOS 11.0, *)) {
extraWidth += self.adjustedContentInset.left + self.adjustedContentInset.right;
} else {
extraWidth += self.contentInset.left + self.contentInset.right;
}
return extraWidth;
}
- (CGFloat)heightPadding
{
CGFloat extraHeight = self.textContainerInset.top + self.textContainerInset.bottom;
if (#available(iOS 11.0, *)) {
extraHeight += self.adjustedContentInset.top + self.adjustedContentInset.bottom;
} else {
extraHeight += self.contentInset.top + self.contentInset.bottom;
}
return extraHeight;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Prevents flashing of frame change
if (CGSizeEqualToSize(self.bounds.size, self.intrinsicContentSize) == NO) {
[self invalidateIntrinsicContentSize];
}
// Fix offset error from insets & safe area
CGFloat textWidth = self.bounds.size.width - [self widthPadding];
CGFloat textHeight = self.bounds.size.height - [self heightPadding];
if (self.contentSize.width <= textWidth && self.contentSize.height <= textHeight) {
CGPoint offset = CGPointMake(-self.contentInset.left, -self.contentInset.top);
if (#available(iOS 11.0, *)) {
offset = CGPointMake(-self.adjustedContentInset.left, -self.adjustedContentInset.top);
}
if (CGPointEqualToPoint(self.contentOffset, offset) == NO) {
self.contentOffset = offset;
}
}
}
- (CGSize)intrinsicContentSize
{
if (self.attributedText.length == 0) {
return CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric);
}
CGRect rect = [self.attributedText boundingRectWithSize:CGSizeMake(self.bounds.size.width - [self widthPadding], CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return CGSizeMake(ceil(rect.size.width + [self widthPadding]),
ceil(rect.size.height + [self heightPadding]));
}
vitaminwater's answer is working for me.
If your textview's text is bouncing up and down during edit, after setting [textView setScrollEnabled:NO];, set Size Inspector > Scroll View > Content Insets > Never.
Hope it helps.
Place hidden UILabel underneath your textview. Label lines = 0. Set constraints of UITextView to be equal to the UILabel (centerX, centerY, width, height). Works even if you leave scroll behaviour of textView.
BTW, I built an expanding UITextView using a subclass and overriding intrinsic content size. I discovered a bug in UITextView that you might want to investigate in your own implementation. Here is the problem:
The expanding text view would grow down to accommodate the growing text if you type single letters at a time. But if you paste a bunch of text into it, it would not grow down but the text would scroll up and the text at the top was out of view.
The solution:
Override setBounds: in your subclass. For some unknown reason, the pasting caused the bounds.origin.y value to be non-zee (33 in every case that I saw). So I overrode setBounds: to always set the bounds.origin.y to zero. Fixed the problem.
Here's a quick solution:
This problem may occur if you have set clipsToBounds property to false of your textview. If you simply delete it, the problem goes away.
myTextView.clipsToBounds = false //delete this line
Obj C:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic) UITextView *textView;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize textView;
- (void)viewDidLoad{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor grayColor]];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(30,10,250,20)];
self.textView.delegate = self;
[self.view addSubview:self.textView];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (void)textViewDidChange:(UITextView *)txtView{
float height = txtView.contentSize.height;
[UITextView beginAnimations:nil context:nil];
[UITextView setAnimationDuration:0.5];
CGRect frame = txtView.frame;
frame.size.height = height + 10.0; //Give it some padding
txtView.frame = frame;
[UITextView commitAnimations];
}
#end

Resources