Implementing auto layout for views generated programmatically

后端 未结 2 368
别跟我提以往
别跟我提以往 2020-12-04 20:48

I have an app whose views are generated programmatically. Example:

-(void)loadView
{
    [super loadView];

// SET TOP LEFT BTN FOR NEXT VIEW
UIBarButtonItem         


        
相关标签:
2条回答
  • 2020-12-04 21:00

    Yes there is, by using two methods in NSLayoutConstraint

    -(NSArray*)constraintsWithVisualFormat:options:metrics:views:
    -(NSLayoutConstraint*)constraintWithItem:attribute:relatedBy:toItem:attribute:
        multiplier:constant:
    

    The visual format language is all packaged up into an NSString So I'll take your iouTableView for example.

    [self.view addConstraints:[NSLayoutConstraint 
        constraintsWithVisualFormat:@"|[iouTableView]|" 
        options:0 
        metrics:nil 
        views:NSDictionaryOfVariableBindings(iouTableView)]];
    

    The pipe symbol "|" represents the superview's edge. The [] represent a view. So what we did there was we hooked the iouTableView's left and right edge to the left and right edge of its superview.

    Another example of the visual format: Let's hook your table view, summary label and summary table vertically.

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:
        @"V:|[iouTableView(348)][summaryTableLabel(18)][summaryTableView(44)]"
        options:NSLayoutFormatAlignAllLeft
        metrics:nil
        views:NSDictionaryOfVariableBindings(iouTableView, summaryTableLabel, summaryTableView)]];
    

    Now this links up all three views vertically on each of their edges, NSLayoutFormatAlignAllLeft tells all the views to align left and they'll do so based on other constraints, in this case, the previous constraint. The ()s are used to specify the size of the views.

    There's a bit more like inequalities and priorities as well as the "-" spacer symbol but check out the apple docs for that

    Edit: Corrected the examples to use constraintsWithVisualFormat as shown in the method signature.

    0 讨论(0)
  • 2020-12-04 21:20

    In addition to Aplle provided methods you can use Parus lib for operating with AutoLayout from code.

    For example you will be able to specify:

    PVVFL(@"[view1]-20-[view2]").fromRightToLeft.withViews(views).asArray
    

    Instead of

    [NSLayoutConstraint constraintsWithVisualFormat:@"[view1]-20-[view2]"
                                            options:NSLayoutFormatDirectionRightToLeft
                                            metrics:nil
                                              views:views]
    

    Also you will be able to group layouts settings, mix VFL and not VFL constraints. Parus able to prevent common mistakes, differentiate location and parameters constriaints, and provide great auto-completion support.

    0 讨论(0)
提交回复
热议问题