Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Applying constraints using code in ios

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 449
    Comment on it

    We can apply constraints with the help of coding also.


    Suppose we have a button and we have to give constraints to it so below coding can help us to do so.
    Lets make a custom button first.

     

    UIButton *firstButton;  
    
    firstButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // providing button shape   
    
    [firstButton setTitle:@"First" forState:UIControlStateNormal]; // title of the button 
    
    [firstButton sizeToFit];    
    
    firstButton.translatesAutoresizingMaskIntoConstraints = NO;   
    
     [self.view addSubview:firstButton]; // adding button on view
    


    Applying constraints by using  NSLayoutConstraint.

    Leading space constraints

    In the below code we are adding constraints on a button(firstButton) and giving leading constraints to it from the super view. Leading space we set i.e 20.     


     

     NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:firstButton attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:20.f];
    
    
    [self.view addConstraint:constraint]; // adding constraints on view     
    
    

      Top space constraints 

    Now we are adding constraints on button(firstButton) and giving top constraints to it from the super view. Top space we set i.e 30.

    constraint = [NSLayoutConstraint constraintWithItem:firstButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:30.f];
    
    
     [self.view addConstraint:constraint]; // adding constraints on view
    
    


    In the same way we can give trailing and bottom space also. If we want to give CenterX or CenterY constraints then we have to use below code.

    CenterX or CenterY constraints

    Below code is for CenterX constraints so that button should display on x axis of the super view.

    constraint = [NSLayoutConstraint constraintWithItem:firstButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];
    
    
    [self.view addConstraint:constraint];

    In the same way we can apply CenterY constraints also as per our need.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: