Objective C: Center with NSLayoutConstraint - ios

NSArray *imageViewHorConst2 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:[_startbutton(50)]-30-[_resetbutton(50)]" options:0 metrics:nil views:viewsDictionary2];}
I'm trying to get those 2 buttons (startbutton, resetbutton) to be separated by some value and be centred.
I'm not sure how to do this in objective C

Here is the snippet to add the two buttons in the center of the screen separated by 30 pixels:
UIButton *button1 = [[UIButton alloc] init];
button1.translatesAutoresizingMaskIntoConstraints = FALSE;
[button1 setTitle:#"Button 1" forState:UIControlStateNormal];
button1.backgroundColor = [UIColor blueColor];
UIButton *button2 = [[UIButton alloc] init];
button2.translatesAutoresizingMaskIntoConstraints = FALSE;
[button2 setTitle:#"Button 2" forState:UIControlStateNormal];
button2.backgroundColor = [UIColor brownColor];
// Add a container view to hold two buttons
UIView *containerView = [[UIView alloc] init];
containerView.translatesAutoresizingMaskIntoConstraints = FALSE;
[containerView addSubview:button1];
[containerView addSubview:button2];
// vertical constraints
[containerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[button1]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button1)]];
[containerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[button2]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button2)]];
// horizontal constraints
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[button1]-(30)-[button2]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button1, button2)]];
// Add the container view with centerx and centery constraints to
// keep the buttons in the center
[self.view addSubview:containerView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:containerView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
Screenshot:

You can easily accomplish this with UIStackView
self.view.backgroundColor = [UIColor redColor];
UIStackView*st = [UIStackView new];
st.distribution = UIStackViewDistributionFillEqually;
st.axis = UILayoutConstraintAxisHorizontal;
st.spacing = 40;
UIButton*b1 = [UIButton buttonWithType:UIButtonTypeSystem];
UIButton*b2 = [UIButton buttonWithType:UIButtonTypeSystem];
[b1 setTitle:#"ClickB1" forState:UIControlStateNormal];
[b2 setTitle:#"ClickB2" forState:UIControlStateNormal];
st.translatesAutoresizingMaskIntoConstraints = NO;
b1.translatesAutoresizingMaskIntoConstraints = NO;
b2.translatesAutoresizingMaskIntoConstraints = NO;
[st addArrangedSubview:b1];
[st addArrangedSubview:b2];
[self.view addSubview:st];
[[st.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES];
[[st.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES];

Related

UITextfield becomes non editable when applying a few constraints

Something strange is happening when I have UITextfield, UILabel and UIButton. I am applying constraints so that the label and the textfield are centred in the UIView. The button is pinned at the bottom. When I run this code, UITextField becomes non-editable. Can somebody tell me what is going wrong with this code below?
Click here to view the code output
UIView* topLayout = [[UIView alloc]init];
[topLayout setTranslatesAutoresizingMaskIntoConstraints:NO];
topLayout.backgroundColor = [UIColor whiteColor];
[self.view addSubview: topLayout];
NSArray *topLayoutHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:[parentView(==mainView)]" options:0 metrics:0 views:#{#"parentView": topLayout, #"mainView":self.view}];
NSArray *topLayoutVConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[parentView]|" options:0 metrics:0 views:#{#"parentView": topLayout}];
[self.view addConstraints:topLayoutHConstraints];
[self.view addConstraints:topLayoutVConstraints];
UIView *childViewLayout = [[UIView alloc]init];
childViewLayout.backgroundColor = [UIColor yellowColor];
[childViewLayout setTranslatesAutoresizingMaskIntoConstraints:NO];
[topLayout addSubview:childViewLayout];
NSLayoutConstraint *childViewControlsHConstraints = [NSLayoutConstraint constraintWithItem:childViewLayout attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:topLayout attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
NSLayoutConstraint *childViewControlsVConstraints = [NSLayoutConstraint constraintWithItem:childViewLayout attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:topLayout attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
NSLayoutConstraint *childViewControlsHtConstraints = [NSLayoutConstraint constraintWithItem:childViewLayout attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:topLayout attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0];
[topLayout addConstraint:childViewControlsHConstraints];
[topLayout addConstraint:childViewControlsVConstraints];
//[topLayout addConstraint:childViewControlsHtConstraints];
// Instruction field
UILabel* instructionFieldLbl = [[UILabel alloc]init];
[childViewLayout addSubview:instructionFieldLbl];
[instructionFieldLbl setText:#"Please check your SMS or E-Mail for the 4 digit actiation code. Please enter the same to activat your account"];
UIFont *instructionFieldLblFont = [UIFont fontWithName:#"Arial-BoldMT" size:13];
[instructionFieldLbl setFont:instructionFieldLblFont];
instructionFieldLbl.numberOfLines = 0;
[instructionFieldLbl sizeToFit];
[instructionFieldLbl setTextColor:[UIColor grayColor]];
instructionFieldLbl.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *instructionFieldHConstraint = [NSLayoutConstraint constraintWithItem:instructionFieldLbl attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationLessThanOrEqual toItem:childViewLayout attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0f];
//NSArray *instructionFieldHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[instructionFieldLbl]-10-|" options:0 metrics:nil views:#{#"instructionFieldLbl": instructionFieldLbl}];
[childViewLayout addConstraint:instructionFieldHConstraint];
//[childViewLayout addConstraints:instructionFieldHConstraints];
dispatch_async(dispatch_get_main_queue(), ^{
instructionFieldLbl.preferredMaxLayoutWidth = self.view.bounds.size.width;
});
// Activation field
self->m_ObjActivationField = [[JVFloatLabeledTextField alloc]init];
[childViewLayout addSubview:self->m_ObjActivationField];
self->m_ObjActivationField.borderStyle = UITextBorderStyleRoundedRect;
self->m_ObjActivationField.translatesAutoresizingMaskIntoConstraints = NO;
self->m_ObjActivationField.placeholder = [NSString stringWithFormat:#"Enter the activtion code"];
NSLayoutConstraint *activationHorzConstraint = [NSLayoutConstraint constraintWithItem:self->m_ObjActivationField attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:childViewLayout attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
[childViewLayout addConstraint:activationHorzConstraint];
NSDictionary *myControlViews = #{
#"instructionFieldLbl": instructionFieldLbl,
#"activationField": self->m_ObjActivationField
};
NSArray *myControlViewsVConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[instructionFieldLbl]-10-[activationField]|" options:0 metrics:nil views:myControlViews];
[childViewLayout addConstraints:myControlViewsVConstraints];
// Submit button
self->m_ObjActivationBut = [[UIButton alloc]init];
[topLayout addSubview:self->m_ObjActivationBut];
[self->m_ObjActivationBut setTitle: [NSString stringWithFormat:#"Activate"] forState:UIControlStateNormal];
self->m_ObjActivationBut.backgroundColor = [UIColor redColor];
[self->m_ObjActivationBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self->m_ObjActivationBut.translatesAutoresizingMaskIntoConstraints = NO;
self->m_ObjActivationBut.layer.cornerRadius = 10;
self->m_ObjActivationBut.clipsToBounds = YES;
NSDictionary *topViews = #{
#"childViewLayout": childViewLayout,
#"activationButton": self->m_ObjActivationBut
};
//NSArray *myTopVConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[activationButton(40)]-10-|" options:0 metrics:nil views:topViews];
NSArray *myTopHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-[activationButton]-|" options:0 metrics:nil views:#{#"activationButton": self->m_ObjActivationBut}];
NSLayoutConstraint *myTopVConstraints = [NSLayoutConstraint constraintWithItem:self->m_ObjActivationBut attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:topLayout attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10.0f];
[topLayout addConstraint:myTopVConstraints];
[topLayout addConstraints:myTopHConstraints];

How to change scrollView content sizes using auto-layouts in ios

I am adding 3 UITextfields and 1 UIButton on my scrollview.
My main requirement is when I click on UITextfield scroll must scroll up-to all fields visible to user above keyboard.
And when I click return button on keyboard scroll must scroll by default what in set for scrollview contentSize using auto-layouts.
my code:
#interface ViewController10 ()
{
UIScrollView * scrollView;
UITextField * emailTextField;
UITextField * nameTextField;
UITextField * passwword;
UIButton * submit;
}
#end
#implementation ViewController10
- (void)viewDidLoad {
[super viewDidLoad];
scrollView = [[UIScrollView alloc] init];
scrollView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:scrollView];
emailTextField = [self createLabelWithText];
emailTextField.delegate = self;
[scrollView addSubview: emailTextField];
nameTextField = [self createLabelWithText];
nameTextField.delegate = self;
[scrollView addSubview: nameTextField];
passwword = [self createLabelWithText];
passwword.delegate = self;
[scrollView addSubview: passwword];
submit = [[UIButton alloc]init];
submit.backgroundColor = [UIColor orangeColor];
[submit setTitle: #"Submit" forState: UIControlStateNormal];
submit.translatesAutoresizingMaskIntoConstraints = NO;
[scrollView addSubview:submit];
NSDictionary * viewsDic = NSDictionaryOfVariableBindings(scrollView,emailTextField,nameTextField,passwword,submit);
//Applying autolayouts for scrolview
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:#"H:|-0-[scrollView]-0-|"]
options:0
metrics:nil
views:viewsDic]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:#"V:|-0-[scrollView]-0-|"]
options:0
metrics:nil
views:viewsDic]];
//Applying autolayouts for textfields and button
[scrollView addConstraint:[NSLayoutConstraint constraintWithItem:emailTextField
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:scrollView
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
NSArray * keys = #[#"emailTextField",#"nameTextField",#"passwword",#"submit"];
for (NSString * key in keys) {
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:#"H:|-10-[%#]-10-|",key]
options:0
metrics:nil
views:viewsDic]];
}
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-30-[emailTextField(30)]-130-[nameTextField(30)]-130-[passwword(30)]-60-[submit(30)]-20-|"
options:0
metrics:nil
views:viewsDic]];
}
-(UITextField *)createLabelWithText{
UITextField * textfield = [[UITextField alloc] init];
textfield.textColor = [UIColor whiteColor];
textfield.backgroundColor = [UIColor lightGrayColor];
textfield.translatesAutoresizingMaskIntoConstraints = NO;
return textfield;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
scrollView.contentSize = CGSizeMake(320, 700);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
Please check this awsome tutorial , it is definetly helpfull for you.
**
Using UIScrollView with Auto Layout in iOS
**
as said in blog you need to set constrain in this way when you are using autolayout.
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeLeading
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0];
[self.view addConstraint:leftConstraint];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:self.contentView
attribute:NSLayoutAttributeTrailing
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0];
[self.view addConstraint:rightConstraint];
change value and name according to your requirement.
When keyBoards is appears .
CGRect frame = currentActiveView.frame; // your scrollview frame
frame.size.height = SCREEN_HEIGHT - 216 - keyboardAccesssory.frame.size.height;
currentActiveView.frame = frame;
[yourScrollView setContentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)];
When keyboard is resign ..
CGRect frame = currentActiveView.frame; // your scrollview frame
frame.size.height = SCREEN_HEIGHT;
currentActiveView.frame = frame;
[yourScrollView setContentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)];
You need to play with the frame of the view.
Move the frame above keyboard when keyboard is shown whereas reset its position when keyboard is hidden.
You need to do it programmatically.
You can also go through Apple's Programming guide. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW3

Objective-C add more UIButton horizontally

I am using a open source UIAlertView.View is
I want to add more button like horizontally, one in left side and another in right of BYE button, like this one
my using source-code are bellow
-(void)popUPView{
UIView* contentView = [[UIView alloc] init];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
contentView.backgroundColor = [UIColor klcLightGreenColor];
contentView.layer.cornerRadius = 12.0;
UILabel* dismissLabel = [[UILabel alloc] init];
dismissLabel.translatesAutoresizingMaskIntoConstraints = NO;
dismissLabel.backgroundColor = [UIColor clearColor];
dismissLabel.textColor = [UIColor whiteColor];
dismissLabel.font = [UIFont boldSystemFontOfSize:32.0];
dismissLabel.text = #"Hi.";
UIButton* dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
dismissButton.translatesAutoresizingMaskIntoConstraints = NO;
dismissButton.contentEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);
dismissButton.backgroundColor = [UIColor klcGreenColor];
[dismissButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[dismissButton setTitleColor:[[dismissButton titleColorForState:UIControlStateNormal] colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
dismissButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
[dismissButton setTitle:#"Bye" forState:UIControlStateNormal];
dismissButton.layer.cornerRadius = 6.0;
[contentView addSubview:dismissLabel];
[contentView addSubview:dismissButton];
NSDictionary* views = NSDictionaryOfVariableBindings(contentView, dismissButton, dismissLabel);
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-(16)-[dismissLabel]-(10)-[dismissButton]-(24)-|"
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:views]];
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-(36)-[dismissLabel]-(36)-|"
options:0
metrics:nil
views:views]];
KLCPopup *popup = [KLCPopup popupWithContentView:contentView
showType:KLCPopupShowTypeShrinkIn
dismissType:KLCPopupDismissTypeShrinkOut
maskType:KLCPopupMaskTypeDimmed
dismissOnBackgroundTouch:TRUE
dismissOnContentTouch:FALSE];
[popup show];
}
would you kindly help me how to solve this problem . Thanks is advance
For this you must set proper leading/trailing values ,
leftView.trailing = rightView.leading
for example if you want to align a new view to the right , you would do something like this
UIView *viewToAllign = yourView;
UIView *view = [[UIView alloc] init];
imageViewOn.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:viewToAllign
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:SPACING_BETWEEN_VIEWS];
or if you want to align something on the left , just switch layout attributes
UIView *viewToAllign = yourView;
UIView *view = [[UIView alloc] init];
imageViewOn.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:viewToAllign
attribute:NSLayoutAttributeLeading
multiplier:1
constant:SPACING_BETWEEN_VIEWS];
then you have to create other constraints ( height , width , top and bottom )
after this , you can add constraints to your container view

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.

Issue with autoLayout and constraints

I have an issue with iOS and AutoLayout...it is a testing application where I have replicated the problem. It consists in a simple view controller, containing a fixed UIButton; when user clicks this button, the delegate have to create a custom view, apply it positioning constraints; the view has then a method to build his content views, and the child views are placed with constraints too.
Here is the code:
//MyViewController.m
#implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *start_but = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
[start_but setTitle:#"Draw" forState:UIControlStateNormal];
[start_but setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
[start_but addTarget:self action:#selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:start_but];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)clickAction: (id)sender
{
localView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 400, 300)];
UIView *superview = (UIView*)localView;
superview.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:localView];
NSLayoutConstraint *constr = [NSLayoutConstraint constraintWithItem:localView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:100.0];
[self.view addConstraint:constr];
constr = [NSLayoutConstraint constraintWithItem:localView
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:-50.0];
[self.view addConstraint:constr];
[localView CreateGuiInterface];
}
#end
//MyView.m
#implementation MyView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code
}
return self;
}
-(void)CreateGuiInterface
{
UIView *superview = self;
self.backgroundColor = [UIColor redColor];
UIButton *but1 = [[UIButton alloc] init];
[but1 setTitle:#"Button" forState:UIControlStateNormal];
[but1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
but1.backgroundColor = [UIColor yellowColor];
but1.translatesAutoresizingMaskIntoConstraints = NO;
[superview addSubview:but1];
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:but1
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeRight multiplier:1.0
constant:-20.0];
[superview addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:but1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:50.0];
[superview addConstraint:constraint];
UILabel *label = [[UILabel alloc] init];
label.text = #"Label";
label.backgroundColor = [UIColor greenColor];
label.textColor = [UIColor blackColor];
label.translatesAutoresizingMaskIntoConstraints = NO;
[superview addSubview:label];
constraint = [NSLayoutConstraint constraintWithItem:label
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:but1
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:-40.0];
[superview addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:label
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:but1
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:20.0];
[superview addConstraint:constraint];
}
#end
So, the problem is that when i click iOS seems to have problem to draw the view background color. It is strange, 'cause if i don't use superview.translatesAutoresizingMaskIntoConstraints = NO and put the view in a fixed place (with initWithFrame:CGRect(100,200,300,400) for example) without using constraints, it works fine: can there be problems using constraints in child and parent views? AppleDoc said that the constraints cannot pass throughout the view barrier; so i've written my app with local-view oriented constraints....
can somebody help me?
thanks in advice
The intent with autoLayout is to never have to setFrame on any of your views. If you want to place your view programatically within your superview, you will provide constraints for that. The changes I made you will see the background red as intended. I didn't change your MyView implementation (simply added -(void)CreateGuiInterface;
within MyView.h). The changes I made to demonstrate are within your MyViewController implementation.
Try the following code in place of your viewController:
#interface MyViewController ()
#property (nonatomic, strong) MyView* localView;
#end
#implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *start_but = [[UIButton alloc] init];
start_but.translatesAutoresizingMaskIntoConstraints = NO;
[start_but setTitle:#"Draw" forState:UIControlStateNormal];
[start_but setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
[start_but addTarget:self action:#selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:start_but];
// The following constraints simply place the initial start button in the top left
NSDictionary* views = NSDictionaryOfVariableBindings(start_but);
NSString* format = #"H:|-[start_but]";
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:0
metrics:nil
views:views];
[self.view addConstraints:constraints];
format = #"V:|-[start_but]";
constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:0
metrics:nil
views:views];
[self.view addConstraints:constraints];
}
- (void)clickAction: (id)sender
{
self.localView = [[MyView alloc] init];
UIView *superview = (UIView*)self.localView;
superview.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.localView];
// Here I'm placing your parent view (MyView) 50 points on right of the superview with
// a width of 400 points
NSDictionary* views = NSDictionaryOfVariableBindings(superview);
NSString* format = #"H:[superview(==400)]-(50)-|";
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:0
metrics:nil
views:views];
[self.view addConstraints:constraints];
// Vertically 100 points from the top of the superview with a height of 300 points
format = #"V:|-(100)-[superview(==300)]";
constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:0
metrics:nil
views:views];
[self.view addConstraints:constraints];
[self.localView CreateGuiInterface];
}
#end

Resources