Search code examples
iosuibuttonautolayoutconstraints

How to add constraints programmatically in ios


I created my UI elements programmatically in ios. Everything is fine in all iphone sices but my buttons get streched.

btnLogin=[[UIButton alloc] initWithFrame:CGRectMake(80, h-90, w-160, 40)]; This is the way Icreated my button. I know In interface builder we can use auto layout. But how can I add constraints to this button programmatically?

Because now the button width changing according to the screen size although the left and right side edges are fixed. How can I avoide the element streatching according to the device and also I want to manage the same gap between left and right side between the button and the parent view border.

How can I do this? Please help me Thanks


Solution

  • This is what you want

     UIButton * button = [[UIButton alloc] init];
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];
    
    NSDictionary * buttonDic = NSDictionaryOfVariableBindings(button);
    button.translatesAutoresizingMaskIntoConstraints = NO;
    
    NSArray * hConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-80-[button]-80-|"
                                                                     options:0
                                                                     metrics:nil
                                                                        views:buttonDic];
    [self.view addConstraints:hConstraints];
    
    NSArray * vConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[button(40)]-90-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:buttonDic];
    [self.view addConstraints:vConstraints];
    

    Screenshot iphone 6

    iPhone 6p

    Update:

    H:|-80-[button]-80-|,this create constraints at horizontal,button left and right to superview keeps to 80

    "V:[button(40)]-90-|",this create constraints at Vertical,button height keeps to 40 and bottoms to superview bottoms keeps to 90