Autolayout in UITextField: Auto Layout still required after executing -layoutSubviews - ios

I'm subclassing UITextField to add a label on the left side. I'm using autolayout to layout the label. However, I keep getting this crash:
Here's how I am doing my layout code:
- (void)updateConstraints {
self.segmentLabel.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *constraint;
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0f];
[self addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.segmentLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.segmentWidth];
[self addConstraint:constraint];
[super updateConstraints];
}
When I don't make any adjustments to the textfield, this works fine.
However, if I try to set the placeholder text, I get this exception:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. DDSegmentedTextField's implementation of -layoutSubviews needs to call super.'
However, I'm not overriding -layoutSubviews.
Has anyone encountered this? What am I doing wrong?
Thanks!

So I ran into this same error a few days ago as well. It turns out I was trying to layout subviews inside my UITextfield subclass, setting properties on them, moving them, etc, but was never explicitly telling the view to lay itself out (i.e. calling [self layoutIfNeeded]).
iOS 8 seems to force to a view to layout all its subviews, and then configures constraints on it. iOS 7 won't, and needs you to explicitly tell views to redraw their subviews when you change if you're using autolayout.
In my case, I had subclassed UITextField and added a label to the side. I configured the frame of the label by adding constraints to the UITextfield. One of the public methods I could call on my class was
- (void)setLabelText:(NSString *)newText{
self.sideLabel.text = newText;
}
This caused my application to crash when a view controller appeared containing my subclassed textfield. By adding layoutIfNeeded everything now works fine in iOS7 and iOS8.
- (void)setLabelText:(NSString *)newText{
self.sideLabel.text = newText;
[self layoutIfNeeded];
}
This needs to be called every time you change a part of the view in your subclass. This includes the setup when you add subviews, when you change view properties, anything really. Before the function that's changing your view returns, call layoutIfNeeded on your view. This seems to apply for a few standard UI controls including UITextfield, UITableView and UICollectionView, though I'm sure there are others. I hope this was clear enough and helped solve your problem.
The error you're getting isn't super useful, and didn't even apply in my case. Though I was receiving the exact same error, none of my views implementing layoutSubviews, and thus were all using the [super layoutSubviews] method.

This problem shows up in iOS < 8
While creating the UIView subclass and adding views, we can instruct the control to construct and autolayout first the subviews.
Use this statement when the UI needs to be updated:
[self layoutIfNeeded];
iOS 8+ are handling the issue quite on there own internally.

I had the same issue. This could be caused by wrong constraints, maybe by some set in Storyboard. Try to remove some of them and see if it works to figure out what's wrong

Related

Prevent calling of viewDidLayoutSubviews on user interaction with iOS 8 custom keyboard

I'm developing an iOS 8 custom keyboard and I'm facing the following issue:
- (void) viewDidLayoutSubviews{} method from UIInputViewController subclass is called each time user touches the keyboard (tap, swipe etc.). I would like to avoid this, there is no need to call it when user touches the keyboard.
Also I found that if I comment the following lines, viewDidLayoutSubviews is not called anymore when user interacts with keyboard:
NSLayoutConstraint *keyboardButtonLeftSideConstraint = [NSLayoutConstraint constraintWithItem:self.customKeyboardView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0];
NSLayoutConstraint *keyboardButtonBottomConstraint = [NSLayoutConstraint constraintWithItem:self.customKeyboardView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0];
[self.view addConstraints:#[keyboardButtonLeftSideConstraint, keyboardButtonBottomConstraint]];
But I can't get rid of these constraints, because I need them to change keyboard's height. How could I solve this?
I highly recommend you not to use viewDidLayoutSubviews(and also viewWillLayoutSubviews) in keyboard extension. They will be called due to frame changing, constraints changing and so many other events, which will sometimes cause unexpected problems. viewDidAppear can be a replacement.
If you really have to override viewDidLayoutSubviews, try use flags to prevent it from getting incorrectly called.
-(void)viewDidLayoutSubviews {
if (self.alreadyLoaded) {
return;
}
else {
//...
}
}

Positioning a view on top of a tableview using Auto Layout

I have a tableview in my storyboard that has its class set to my UITableView subclass which is named SPSExplanationTableView. There are no constraints set on this tableview in Interface Builder.
I am trying to programmatically create a UIView that displays in front of the tableview—which I know how to do (blog post link)—but that is sized and positioned using Auto Layout. This is my code:
#import "SPSExplanationTableView.h"
#interface SPSExplanationTableView()
#property (nonatomic, strong) UIView *explanationView;
#end
#implementation SPSExplanationTableView
- (void)awakeFromNib
{
[super awakeFromNib];
self.explanationView = [[UIView alloc] init];
self.explanationView.translatesAutoresizingMaskIntoConstraints = NO;
self.explanationView.backgroundColor = [UIColor blueColor];
[self addSubview:self.explanationView];
[self bringSubviewToFront:self.explanationView];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f constant:150.0f];
[self.explanationView addConstraint:heightConstraint];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f constant:200.0f];
[self.explanationView addConstraint:widthConstraint];
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.0f constant:0.0f];
[self addConstraint:topConstraint];
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.explanationView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.0f constant:0.0f];
[self addConstraint:leftConstraint];
#end
When I run the app it crashes with the following assertion failure:
*** Assertion failure in -[SPSExplanationTableView layoutSublayersOfLayer:],
/SourceCache/UIKit_Sim/UIKit-2935.137/UIView.m:8794
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still
required after executing -layoutSubviews. SPSExplanationTableView's
implementation of -layoutSubviews needs to call super.'
Taking the message literally and overriding layoutSubviews has no effect i.e. I still get the same crash.
- (void)layoutSubviews
{
[super layoutSubviews];
}
What's the correct way to implement what I'm trying to achieve?
For Aubada Taljo, here's the tableview in Interface Builder:
Update: I solved this myself in the end by not using Auto Layout! I overrode the layoutSubviews method in my SPSExplanationTableView class and set the center property of the explanationView to the centre of self's bounds, with some slight adjustments to the y-axis position to make it look how I wanted it.
This is crashing because UITableViews are not designed to do this. A UITableView is only concerned about its cells, the headers, maybe its background, and it has logic for this that doesn't use autolayout. So it will crash if you try to involve it in any constraints calculation between it and any subviews, e.g. this will also crash if you add a constraint between the cell and the table.
What I suggest you do is to add a superview that will contain both your table and the view that you want to overlay:
SuperviewWithConstraints
|
|-- YourTableViewWithConstraintsRelativeToSuperview
|
|-- YourOverlayWithConstraintsRelativeToSuperview
And set up the constraints there. Then make that superview as your view controller's view. You will have to move away from using the UITableViewController as the controlling class, though.
If you would take my advice and make your life easier, simply go to your storyboard in Interface Builder and set the correct constraints on the your table view, now go back to the code editor and in the UIViewController that owns your table view, write the view creation code in viewDidLoad e.g.
UIView* someView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height)];
[self.view addSubView someView];
I guess this should be more than enough to solve your issue, now if you face any problems, move your code to viewDidLayoutSubViews in the UIViewController
Please tell me if you need more details but I use this way of creating dynamic controls all the time.

Why am I getting a "Auto Layout still required after executing -layoutSubviews" error every time my app launches now?

Since I added the following code, every time my app opens this UITableViewController it crashes:
self.noArticlesView = [[UIView alloc] init];
self.noArticlesView.translatesAutoresizingMaskIntoConstraints = NO;
self.noArticlesView.backgroundColor = [UIColor colorWithRed:0.961 green:0.961 blue:0.961 alpha:1];
[self.view addSubview:self.noArticlesView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.noArticlesView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.noArticlesView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.noArticlesView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.noArticlesView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
And it gives me this error:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'
What on earth am I doing wrong? I call that code in tableView:numberOfRowsInSection: when there's 0 rows.
I was subclassing UIScrollView and received the same error message on iOS 7 (but not 8).
I was overriding layoutSubviews in a manner similar to the following:
- (void)layoutSubviews {
[super layoutSubviews];
// code to scroll the view
}
I resolved the issue by moving the call to super's layoutSubviews to be the last thing in the method:
- (void)layoutSubviews {
// code to scroll the view
[super layoutSubviews];
}
Had the same problem. Added view(s) to self.tableView and used constraints. Do not add the views to the table view via addSubview: but add them as header(s), footer(s) or cells.
[self.view layoutIfNeeded]
Hope this helps
You also need to disable mask translation for the table view.
for me is was this
self.tableView.backgroundView = self.emptyView;
I changed to this
NSComparisonResult order = [[UIDevice currentDevice].systemVersion compare: #"8.0" options: NSNumericSearch];
if (order == NSOrderedSame || order == NSOrderedDescending) {
// OS version >= 8.0
self.tableView.backgroundView = self.emptyView;
}else{
[self.tableView.backgroundView addSubview:self.emptyView];
}
Checkout "Auto Layout still required after executing -layoutSubviews" with UITableViewCell subclass as the question appears to be the same.
I was able to implement the category mentioned in one of the answers which solved the problem for me. However, I had to create the category on the UITableView class instead of the UITableViewCell class as is discussed in that particular answer.
You can add your 'no articles view' as a custom header in the table to make sure it's positioned correctly.
A possible solution is not to add the noArticlesView directly in the table, but is to put the UITableView inside a container UIView (eventually setting table constraints to fit with the container frame) and then constraint your noArticlesView to the container, using the same constraints you set and in the same place in your code, that is inside the -tableView:numberOfRowsInSection: UITableViewDataSource method.
I tested it with a simple example, and it worked.
The changes you need to apply to your code are to replace the UITableViewController with a UIViewController, add a container view (unless you want your table to fit exactly with the view controller's view, in such case this view is the container) and then constraint your noArticleView to the container instead of the table.
My example code is at the bottom of this answer.
I will try to make a possible explanation of the reason of the issue and why this solution works, but consider that part of my explanation is based on guesses so it couldn't be completely exact.
First of all a brief explanation of how the view hierarchy rendering process works in iOS. The first step for the layout engine is to determine the size and position of all views and subviews in the view hierarchy. Usually this is done with an iterative approach, where auto layout constraints are evaluated, in order to determine size and position of views and subviews, and then each view's -layoutSubviews method is called for fine tuning: this means that you can change your layout after constraints are evaluated. What the layout engine requires is that if the -layoutSubviews method changes constraints again, then -[super layoutSubviews] must be called again to allow the iterative process: if this doesn't happen the layout engine raises an exception. In the case of the UITableView my guess is that the tableView:numberOfRowsInSection: method is called somewhere within the internal UITableView layoutSubviews method and this method doesn't call [super layoutSubviews]. So if your table data source method updates internal table constraints, at the end of the method the exception is triggered. The solution I propose works because the only constraint applied to the table is the external constraint towards the container, so evaluated at the first stage of the layout process, while the constraints added in the table data source method are not relevant to the table as they are applied to views external to the table (container and noArticlesView) so they don't affect the internal table view layout process.
//
// RootController.h
#import
#interface RootController : UIViewController
#property (nonatomic,strong) IBOutlet UITableView *table;
#property (nonatomic,strong) IBOutlet UIView *container;
#end
//
// RootController.m
#import "RootController.h"
#implementation RootController
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
UIView *_v = [[UIView alloc] init];
_v.backgroundColor=[UIColor redColor];
_v.translatesAutoresizingMaskIntoConstraints=NO;
[self.container addSubview:_v];
NSLayoutConstraint *_c1 = [NSLayoutConstraint constraintWithItem:_v
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.container attribute:NSLayoutAttributeTop multiplier:1.0 constant:20.0];
NSLayoutConstraint *_c2 = [NSLayoutConstraint constraintWithItem:_v
attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.container attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-20.0];
NSLayoutConstraint *_c3 = [NSLayoutConstraint constraintWithItem:_v
attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.container attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20.0];
NSLayoutConstraint *_c4 = [NSLayoutConstraint constraintWithItem:_v
attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.container attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20.0];
[self.container addConstraints:#[_c1,_c2,_c3,_c4]];
return 0;
}
I unchecked auto layout on the view controller the crash is not occurring now

iOS - constraints animate in an unexpected way in viewdidload?

I'm practicing auto layout and learning about animating constraints.
My first question is. If I am dynamically adding views it seems cumbersome to dynamically add their constraints to the parent view as well. Is there any clean way to accomplish a flexible layout where views can be added and removed programmatically? Or would this mean I should probably think of a simpler solution for what I'm trying to accomplish?
Second question. I have created two views, and some constraints in code. I am just trying to resize the height constraint on the first view on load so that it will become shorter, and the second view will shift upwards accordingly.
here is some code:
first = [[UIView alloc]initWithFrame:CGRectZero];
[first setBackgroundColor:[UIColor blueColor]];
[first setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:first];
UIView *second = [[UIView alloc]initWithFrame:CGRectZero];
[second setBackgroundColor:[UIColor redColor]];
[second setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:second];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:first attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:20];
NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:first attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1 constant:-20];
top = [NSLayoutConstraint constraintWithItem:first attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:40];
height = [NSLayoutConstraint constraintWithItem:first attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:80];
[self.view addConstraints:#[leading,trailing,top,height]];
[height setConstant:10];
[UIView animateWithDuration:0.5 animations:^{
[self.view layoutIfNeeded];
}];
okay so at the bottom here I run my animation.. my second view is already positioned where it would be at the end of the animation. the first view expands from its top left corner, to its bottom right corner. it animates diagonally and ends up with a height of 10.
Can anyone explain this behavior. I noticed if I assign the constraints, and make them animate on an IBAction (button touch) then it will animate as expected.
Second question first. Why are you animating changing in viewDidLoad? At this point we know the view is loaded, but it probably isn't laid out and definitely not going to be visible to the user; consider the constraint layout changes in the viewDidLayoutSubviews method.
As for the first question. David H's answer is one way... and a perfectly fine way. To give a different option, I use constraintsWithVisualFormat:options:metrics:views: which allows me to specify views, then creates all the necessary constraints across all the views. It can be a much simpler way to create constraints across several views. Depending on exactly what you are doing one way might better suit your needs.
Edit based on comment...
With something where you'll have to break constraints, you'll still have to find and break the constraints before creating the new ones. There is no way around that. You'll either have a reference to the constraint you want to break or have to iterate through all the constraints on an object to find it. A B C goes to A B and C where the constraint between B and C is gone. Using the visual format to put in X might be something like #"[B]-20-[X]-20-[C]" which will create a constraint for a 20 point spacing between B and X and a second constraint which will be a 20 point spacing between X and C. As a note, the visual format above specifies horizontal positioning/spacing only. You would need a second line to specify the vertical constraints.
I am doing something similar to this, and the technique can be extended. For each view (really, any object), create a mutable dictionary with a "view" and a "constraints" property. the view is just the view, the constraints are an array of dictionaries containing two objects, a "view" property, and a "constraint" property.
When you decide to add or pull a view, then find the dictionary with the appropriate view property, then interate over the constraints array, and add/remove the constraint (of type NSLayerConstraint) to the sister "view" property in the dictionary.
In this manner you can in one method add and remove all the proper constraints regardless of what they view they affect.
Obviously you need to only have constraints that reference views still in the primary view. However, another way to deal with that is to set the width/height of a view to 0, its still there but is not visible. Or change its alpha to 0.

iOS UITableView override autolayout constraints programatically after setTableHeaderView

Okey so this is my dilemma atm.
I have a storyboard with a UITableView (tableView) and UIView (viewForTableHeader) that contains several other objects like a UIImag a label and such.
Programatically I set the UIView to be the header of the UITableView by doing:
[self.tableView setTableHeaderView:self.viewForTableHeader];
This works perfectly when Not using the autolayout.
But with autolayout the app crashes and leaves me with:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'
So in viewDidLoad I have tried to set the constraints of the viewForTableHeader to be:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.viewForTableHeader attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeTop multiplier:0 constant:0];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.viewForTableHeader attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeLeft multiplier:0 constant:0];
[self.view addConstraint:constraint];
and I also tried:
- (void)layoutSublayersOfLayer:(CALayer *)layer {
[super layoutSublayersOfLayer:self.tableView.layer];
and did same thing trying to set the constraints here
}
Is it maby better to have the viewForTableHeader in a nib file?
I do am a bit noobish at this so realy any help or pointers would be helpful.
Since you have both (the tableView and the headerView) in IB, you can drag the viewForTableHeader to (over) the tableView and set it as table header.
This will make the headerView appear below the tableView in the views hierarchy.
If you do this you'll be able to remove/add this view to the table later during run time with no auto layout errors or extra constraints.
[self.viewForTableHeader removeFromSuperview];
and later
[self.tableView setTableHeaderView:self.viewForTableHeader];

Resources