UIView breaking in iOS7 but not in iOS8 - ios

I have created a custom view to show 2 labels inside a circle. It is suppose to look like this:
but in iOS 7 it looks like this:
That happens because the constraints hat are supposed to stick the labels to the top/bottom are breaking for some reason, but only on iOS 7. I get the following error:
(
"<NSLayoutConstraint:0x7f96e500a540 H:|-(-1)-[UILabel:0x7f96e2dd84d0] (Names: '|':UIView:0x7f96e2df6350 )>" )
Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7f96e500a540 H:|-(-1)-[UILabel:0x7f96e2dd84d0] (Names: '|':UIView:0x7f96e2df6350 )>
I have confirmed that those are in fact the constraints called (I only gave one error as an example)
self.dayLabelStickButtomConstraint
self.monthLabelStickTopConstraint
Here is the code for the custom view, can anyone maybe understand why is it breaking on iOS 7 but not on 8?
- (instancetype) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initiateValues];
[self buildHeirarchy];
}
return self;
}
- (instancetype) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initiateValues];
[self buildHeirarchy];
}
return self;
}
-(void)initiateValues{
self.fillColor = [UIColor blackColor];
self.month = #"jan";
self.monthFontSize = 8.0f;
self.monthTextColor = [UIColor blackColor];
self.monthLabelInsetDistance = 1.0f;
self.day = #"01";
self.dayFontSize = 12.0f;
self.dayTextColor = [UIColor blackColor];
self.dayLabelInsetDistance = 1.0f;
}
-(void)buildHeirarchy{
self.innerContainer = [[UIView alloc] initWithFrame:CGRectInset(self.bounds, 5.0, 5.0)];
[self.innerContainer setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.innerContainer];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.innerContainer
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.innerContainer
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.innerContainer
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeWidth
multiplier:0.7
constant:0.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.innerContainer
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeHeight
multiplier:0.7
constant:0.0]];
self.monthLabel = [[UILabel alloc] initWithFrame:CGRectInset(self.bounds, 5.0, 5.0)];
[self.monthLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
self.monthLabel.textAlignment = NSTextAlignmentCenter;
[self.innerContainer addSubview:self.monthLabel];
[self.innerContainer addConstraint:[NSLayoutConstraint constraintWithItem:self.monthLabel
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.innerContainer
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
NSLayoutConstraint *monthTopConstraint = [NSLayoutConstraint constraintWithItem:self.monthLabel
attribute:NSLayoutAttributeTopMargin
relatedBy:NSLayoutRelationEqual
toItem:self.innerContainer
attribute:NSLayoutAttributeTopMargin
multiplier:1.0
constant:self.monthLabelInsetDistance];
self.monthLabelStickTopConstraint = monthTopConstraint;
[self.innerContainer addConstraint:self.monthLabelStickTopConstraint];
self.dayLabel = [[UILabel alloc] initWithFrame:CGRectInset(self.bounds, 5.0, 5.0)];
[self.dayLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.innerContainer addSubview:self.dayLabel];
self.dayLabel.textAlignment = NSTextAlignmentCenter;
[self.innerContainer addConstraint:[NSLayoutConstraint constraintWithItem:self.dayLabel
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.innerContainer
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
NSLayoutConstraint *dayButtomConstraint = [NSLayoutConstraint constraintWithItem:self.dayLabel
attribute:NSLayoutAttributeBottomMargin
relatedBy:NSLayoutRelationEqual
toItem:self.innerContainer
attribute:NSLayoutAttributeBottomMargin
multiplier:1.0
constant:self.dayLabelInsetDistance];
self.dayLabelStickButtomConstraint = dayButtomConstraint;
[self.innerContainer addConstraint:self.dayLabelStickButtomConstraint];
}
-(void)layoutSubviews{
// get the graphics context
if (!self.backgroundColorRoundView) {
self.backgroundColorRoundView = [[UIView alloc]initWithFrame:self.bounds];
[self addSubview:self.backgroundColorRoundView];
[self sendSubviewToBack:self.backgroundColorRoundView];
self.backgroundColorRoundLayer = [CAShapeLayer new];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.backgroundColorRoundView.bounds];
self.backgroundColorRoundLayer.path = path.CGPath;
//imageMaskLayer.fillColor = self.fillColor.CGColor;
[self.backgroundColorRoundView.layer addSublayer:self.backgroundColorRoundLayer];
}
self.backgroundColorRoundView.frame = self.bounds;
self.backgroundColorRoundLayer.frame = self.bounds;
[self updateViews];
[super layoutSubviews];
}
-(void)updateViews{
self.monthLabel.textColor = self.monthTextColor;
self.dayLabel.textColor = self.dayTextColor;
self.backgroundColorRoundLayer.fillColor = self.fillColor.CGColor;
}
-(void)updateConstraints{
self.dayLabelStickButtomConstraint.constant = self.dayLabelInsetDistance;
self.monthLabelStickTopConstraint.constant = self.monthLabelInsetDistance;
[super updateConstraints];
}

After a lot of messing around the answer lied in the restraints themselves. Once i switched from topMargin,bottomMargin to just top and bottom it worked

Related

Change Frame of Subview in Superview

I have a ViewController that adds an UIView, SpeciesImageView as a subview in viewDidLoad and set constraints in viewWillLayoutSubviews.
SpeciesImageView does not have a nib file. When we create speciesImageView in viewDidLoad, it calls initWithFrame in SpeciesImageView class.
This works fine (in both landscape and portrait) until the phone rotates. I tried setting the constraints as speciesImageView.frame.size.width, but that doesn't work because initWithFrame isn't called when the orientation changes, so the height/width of the speciesImageView remains unchanged.
On the other hand, using screenRect doesn't change the actual size of the UIView, it changes its size within the superview. So in other words, I haven't found a way to change the size of the actual speciesImageView on orientation change.
And for reasons lost to me, it gets completely messed up when you rotate it back to the original position.
- (void)viewDidLoad
{
self.tabBarController.tabBar.hidden=YES;
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.hidden = NO;
//self.navigationController.navigationBar.translucent = YES;
UIImage *plantinfo;
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
plantinfo = [UIImage imageNamed:#"plantinfo_frame.png"];
} else {
plantinfo = [UIImage imageNamed:#"plantinfo.png"];
}
UIBarButtonItem *tempButton = [[UIBarButtonItem alloc] initWithImage:plantinfo
style:UIBarButtonItemStylePlain
target:self
action:#selector(toggleText:)];
self.navigationItem.rightBarButtonItem = tempButton;
[tempButton release];
self.title = theSpecies.scientificName;
//[self.navigationItem.backBarButtonItem setTitle:#""];
self.navigationItem.backBarButtonItem.title = #"";
infoViewSegmentedControl.backgroundColor = [UIColor blackColor];
webView.backgroundColor = [UIColor blackColor];
_activityIndicator.hidden = YES;
[webView setOpaque:YES];
webView.delegate = self;
// Do double justification
[webView loadHTMLString:[self formatHTML:theSpecies] baseURL:nil];
showingInfoView = NO;
//
// Resize containerView, infoview according to iphone 5 screen size.
//
infoView.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
CGPoint screenOrigin = [[UIScreen mainScreen] bounds].origin;
CGSize viewSize = [[UIScreen mainScreen] bounds].size;
CGPoint origin = infoView.frame.origin;
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
infoView.frame = CGRectMake(screenOrigin.x,
screenOrigin.y + statusBarFrame.size.height,
viewSize.width,
viewSize.height - origin.y - statusBarFrame.size.height);
speciesImageView = [[SpeciesImageView alloc]
initWithFrame:CGRectMake(screenOrigin.x,
screenOrigin.y,
viewSize.width,
viewSize.height)];
} else {
infoView.frame = CGRectMake(screenOrigin.x,
screenOrigin.y,
viewSize.width,
viewSize.height - origin.y - statusBarFrame.size.height);
speciesImageView = [[SpeciesImageView alloc]
initWithFrame:CGRectMake(screenOrigin.x,
screenOrigin.y,
viewSize.width,
viewSize.height - statusBarFrame.size.height)];
}
speciesImageView.delegate = self;
[containerView addSubview:speciesImageView];
managedObjectContext = [(LeafletAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
[self parseImageURLArray];
}
-(void)viewWillLayoutSubviews{
if(speciesImageView.window != nil){
CGRect screenRect = [[UIScreen mainScreen] bounds];
speciesImageView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *widthConst = [NSLayoutConstraint
constraintWithItem:speciesImageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:screenRect.size.width];
NSLayoutConstraint *heightConst = [NSLayoutConstraint
constraintWithItem:speciesImageView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:screenRect.size.height];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint
constraintWithItem:speciesImageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0];
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint
constraintWithItem:speciesImageView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];
[self.view addConstraints:#[widthConst, heightConst, bottomConstraint, rightConstraint]];
}
}
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
imageScrollView = [[UIScrollView alloc] initWithFrame:frame];
imageScrollView.delegate = self;
imageScrollView.backgroundColor = [UIColor blackColor];
[self addSubview:imageScrollView];
imageScrollView.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *widthConst = [NSLayoutConstraint constraintWithItem:imageScrollView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:imageScrollView.frame.size.width];
NSLayoutConstraint *heightConst = [NSLayoutConstraint constraintWithItem:imageScrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:imageScrollView.frame.size.height];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint
constraintWithItem:imageScrollView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0];
NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint
constraintWithItem:imageScrollView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0];
[self addConstraints:#[widthConst, heightConst, bottomConstraint, rightConstraint]];
}
return self;
}
If you want your views to adjust to the size of the superview,
then you need something like this (set the margin to whatever you like):
CGFloat margin = 0;
NSString * visualFormatH = [NSString stringWithFormat:#"|-(%f)-[speciesImageView]-(%f)-|", margin, margin];
[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualFormatH
options:0
metrics:Nil
views:#{#"speciesImageView": speciesImageView}]];
NSString * visualFormatV = [NSString stringWithFormat:#"V:|-(%f)-[speciesImageView]-(%f)-|", margin, margin];
[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualFormatV
options:0
metrics:Nil
views:#{#"speciesImageView": speciesImageView}]];
Now speciesImageView will adjust its frame whenever the superview frame changes.
Here is a generic example:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView * sampleView = [UIView new];
sampleView.backgroundColor = [UIColor redColor];
sampleView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:sampleView];
CGFloat margin = 0;
NSString * visualFormatH = [NSString stringWithFormat:#"|-(%f)-[sampleView]-(%f)-|", margin, margin];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualFormatH
options:0
metrics:Nil
views:#{#"sampleView": sampleView}]];
NSString * visualFormatV = [NSString stringWithFormat:#"V:|-(%f)-[sampleView]-(%f)-|", margin, margin];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualFormatV
options:0
metrics:Nil
views:#{#"sampleView": sampleView}]];
}
Auto Layout Getting Started
Auto Layout Visual Format Documentation

Instance variable used while 'self' is not set to the result of [(super or self) init…]

My Code :
- (instancetype)initWithSender:(UIView*)sender withSuperView:(UIView*)superView withItems:(NSMutableArray*)items
{
self = [CustomDropdownView loadInstanceFromNibWithiPad:NO];
if (self) {
self.frame = CGRectZero;
[self.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[self.layer setBorderWidth:1.0];
CGRect positionInSuper = [superView convertRect:sender.frame fromView:sender.superview];
float height = superView.frame.size.height - positionInSuper.origin.y;
if (height > 200.0) {
// height = 200.0;
}
[superView addSubview:self];
self.translatesAutoresizingMaskIntoConstraints = NO;
self.constLeading = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:positionInSuper.origin.x];
self.constTop = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1.0 constant:positionInSuper.origin.y + sender.frame.size.height];
self.constWidth = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:sender.frame.size.width];
self.constHeight = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0];
[superView addConstraints:#[self.constLeading, self.constTop]];
[self addConstraints:#[self.constWidth, self.constHeight]];
[self layoutIfNeeded];
self.arrItems = [[NSMutableArray alloc]initWithArray:items];
[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DropDownTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([DropDownTableViewCell class])];
[self.tableView reloadData];
}
return self;
}
The first line
self = [CustomDropdownView loadInstanceFromNibWithiPad:NO];
is very problematic. You should only assign the result of another init method, usually [super init]. Change this to a class method.
By the way, that's what the error message says.

How to add custom view with autolayout programmatically

My storyboard has a single view controller containing a UIScrollView. I want to add some custom view (each view will contain a image & label) to the scrollview programmatically in the viewController. I have set constraints to the UIScrollView in the storyboard but struggling to add custom views with constraints. How can i do this so that it can be appeared as same for all the devices (iPhone/iPad) ? I tried like below but it does not seems to be working.
In My ViewController.m -
#import "MainViewController.h"
#define DEFAULT_ROW_HEIGHT 50
#interface MainViewController ()
#property float topMarginFromUpperView;
#end
#implementation MainViewController
-(void) addCustomRowToView {
self.topMarginFromUpperView += DEFAULT_ROW_HEIGHT + 10.0f;
UIView *customRow = [[UIView alloc] initWithFrame:self.scrollView.bounds];
customRow.backgroundColor = [UIColor redColor];
[self.scrollView addSubview:customRow];
customRow.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTop multiplier:1.0f constant:self.topMarginFromUpperView]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:10.0f]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-10.0f]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeHeight multiplier:0.1f constant:0.0f]];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.topMarginFromUpperView = 0.0f;
for (NSInteger i =0; i< 10; i++) {
[self addCustomRowToView];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
EDITED :
Still struggling with constraint setting. App crashes due to invalid constraint. Tried as below -
-(void) setConstraints:(UIView *)customRow {
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTop multiplier:1.0f constant:self.topMarginFromSuperView]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeLeading multiplier:1.0f constant:10.0f]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-10.0f]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:customRow attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeHeight multiplier:0.1f constant:0.0f]];
}
-(void) addCustomRowToView {
UIView *customRow = [[UIView alloc]initWithFrame:CGRectMake(DEFAULT_PADDING, self.topMarginFromSuperView, self.view.bounds.size.width - 2*DEFAULT_PADDING, DEFAULT_ROW_HEIGHT)];
customRow.backgroundColor = [UIColor redColor];
customRow.translatesAutoresizingMaskIntoConstraints = NO;
[self setConstraints:customRow];
[self.scrollView addSubview:customRow];
self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, self.topMarginFromSuperView + DEFAULT_ROW_HEIGHT);
self.topMarginFromSuperView += DEFAULT_ROW_HEIGHT + DEFAULT_PADDING;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.topMarginFromSuperView = 0.0f;
//for (NSInteger i =0; i< 10; i++) {
[self addCustomRowToView];
// }
}
#end
Here is solution for your problem:
- (void)addCustomView
{
UIView *lastView;
for (int i = 0; i<10; i++)
{
UIView *view = [[UIView alloc] init];
view.backgroundColor = i%2 ? [UIColor redColor] : [UIColor greenColor];
view.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:view];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[view]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
[self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.scrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:-20.0]];
if (i == 0)
{
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view(40)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
}
else
{
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[lastView(40)]-10-[view(40)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lastView,view)]];
}
lastView = view;
}
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:[lastView(40)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(lastView)]];
}

iOS Auto layout Rows

I'm trying to understand auto layout better and I created some static methods that can help me out. Now I'm trying to setup an array of views in like a tableview structure (in rows). This works kinda.
See here my problem:
To achieve this I use this code:
//In the update constraints method
UIView *view1 = [self createView];
view1.backgroundColor = [UIColor redColor];
UIView *view2 = [self createView];
view2.backgroundColor = [UIColor yellowColor];
[self addSubview:view1];
[self addSubview:view2];
[self addConstraints:[DXVFL row:#[view1, view2] inView:self]];
//The row method
+ (NSArray *) row:(NSArray const *)views inView:(UIView const *)superview {
NSMutableArray *constraints = [NSMutableArray new];
CGFloat multiplier = 1.f / [views count];
UIView *prev = nil;
for (UIView *view in views) {
if (!view.hidden) {
[constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeWidth multiplier:1.f constant:0.f]];
[constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0.f]];
if (prev) {
[constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:prev attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]];
}
prev = view;
}
}
return [constraints copy];
}
So this part works (I guess). But when I want to split the yellow view again in rows. The views are always added into the top region?
In the update constraints method I do this:
UIView *view1 = [self createView];
view1.backgroundColor = [UIColor redColor];
UIView *view2 = [self createView];
view2.backgroundColor = [UIColor yellowColor];
[self addSubview:view1];
[self addSubview:view2];
UIView *view3 = [self createView];
UIView *view4 = [self createView];
[view2 addSubview:view3];
[view2 addSubview:view4];
[self addConstraints:[DXVFL row:#[view1, view2] inView:self]];
[view2 addConstraints:[DXVFL row:#[view3, view4] inView:view2]];
But I want those two rows in the bottom? What am I doing wrong?
Off the top of my head:
You need to add a constraint to tell it to align the view to the top of the superview. At the moment, you just set the height and width but you don't tell it where to put its top edge.
Try changing your code to this:
if (!prev) {
[constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeTop multiplier:1.f constant:0.f]];
} else {
[constraints addObject:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:prev attribute:NSLayoutAttributeBottom multiplier:1.f constant:0.f]];
}

NSLayoutConstraints to UITextField - Error

I have a simple setup with 3 views:
view, which has 1 subview contentView, which has 1 subview emailField (a UITextField).
emailfField is not aligning in centerY correctly. I got is this error:
"<NSLayoutConstraint:0x9e7d500 UIView:0x9e85c30.centerY == UITextField:0x9e4dbd0.centerY>",
"<NSLayoutConstraint:0x9e7cc00 UIView:0x9e85530.top == UIView:0x9e85c30.top>",
"<NSAutoresizingMaskLayoutConstraint:0x9e7f950 h=--& v=--& UITextField:0x9e4dbd0.midY == + 282.5>",
"<NSAutoresizingMaskLayoutConstraint:0x9e81e90 h=--& v=--& UIView:0x9e85c30.midY == + 240>")
My .m file:
- (void)viewDidLoad {
[super viewDidLoad];
[self initContentView];
[self initFirstView];
[self addConstraints];}
- (void)addConstraints {
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0]];
//First View
//Email Field
[self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.emailField
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.contentView
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0]];}
- (void)initContentView {
self.view.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0];
self.contentView = [[UIView alloc] initWithFrame:self.view.frame];
self.contentView.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.contentView];
int frameHorizontalCenter = self.contentView.frame.size.width/2;
self.funView = [[UIImageView alloc] initWithFrame:CGRectMake(frameHorizontalCenter-50, 100, 100, 100)];
self.funView.backgroundColor = [UIColor clearColor];
self.funView.image = [UIImage imageNamed:#"dog1"];
[self.contentView addSubview:self.funView];
self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(frameHorizontalCenter - 140, self.funView.frame.origin.y + self.funView.frame.size.height, 280, 60)];
self.descriptionLabel.font = [UIFont systemFontOfSize:14];
self.descriptionLabel.textColor = [UIColor colorWithRed:63.0f/255.0f green:63.0f/255.0f blue:63.0f/255.0f alpha:1.0];
self.descriptionLabel.backgroundColor = [UIColor clearColor];
self.descriptionLabel.highlightedTextColor = [UIColor whiteColor];
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.numberOfLines = 2;
self.descriptionLabel.adjustsFontSizeToFitWidth = YES;
self.descriptionLabel.textAlignment = NSTextAlignmentCenter;
[self.contentView addSubview:self.descriptionLabel];
self.emailField = [[UITextField alloc] initWithFrame:CGRectMake(frameHorizontalCenter -140, self.descriptionLabel.frame.origin.y + self.descriptionLabel.frame.size.height, 280, 45)];
self.emailField.borderStyle = UITextBorderStyleNone;
self.emailField.textColor = [UIColor colorWithRed:63.0f/255.0f green:63.0f/255.0f blue:63.0f/255.0f alpha:1.0];
self.emailField.backgroundColor = [UIColor whiteColor];
self.emailField.placeholder = #"Epasts";
[self.contentView addSubview:self.emailField];}
I really don't understand what's wrong. Aren't constraints set correctly?
Use setTranslatesAutoresizingMaskIntoConstraints: to turn off conversion of autoresizing masks to constraints on contentView and emailField. Add additional constraints to emailField to specify the x position, width and height that it should use.

Resources