[FIXED] Fügen Sie programmgesteuert Ansichten in UIStackView hinzu

Ausgabe

Ich versuche, Ansichten in UIStackView programmgesteuert hinzuzufügen. Für jetzt ist mein Code:

UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 100, 100)];

UIView *view2 =  [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];

[self.stack1 addArrangedSubview:view1];
[self.stack1 addArrangedSubview:view2];

Wenn ich die App bereitstelle, gibt es nur 1 Ansicht und sie ist schwarz. (Ansicht1 erhält auch die Parameter für Ansicht2)

Lösung

Stapelansichten verwenden die intrinsische Inhaltsgröße, verwenden Sie also Layouteinschränkungen, um die Abmessungen der Ansichten zu definieren.

Es gibt eine einfache Möglichkeit, Einschränkungen schnell hinzuzufügen (Beispiel):

[view1.heightAnchor constraintEqualToConstant:100].active = true;

Vollständiger Code:

- (void) setup {

    //View 1
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    [view1.heightAnchor constraintEqualToConstant:100].active = true;
    [view1.widthAnchor constraintEqualToConstant:120].active = true;


    //View 2
    UIView *view2 = [[UIView alloc] init];
    view2.backgroundColor = [UIColor greenColor];
    [view2.heightAnchor constraintEqualToConstant:100].active = true;
    [view2.widthAnchor constraintEqualToConstant:70].active = true;

    //View 3
    UIView *view3 = [[UIView alloc] init];
    view3.backgroundColor = [UIColor magentaColor];
    [view3.heightAnchor constraintEqualToConstant:100].active = true;
    [view3.widthAnchor constraintEqualToConstant:180].active = true;

    //Stack View
    UIStackView *stackView = [[UIStackView alloc] init];

    stackView.axis = UILayoutConstraintAxisVertical;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 30;


    [stackView addArrangedSubview:view1];
    [stackView addArrangedSubview:view2];
    [stackView addArrangedSubview:view3];

    stackView.translatesAutoresizingMaskIntoConstraints = false;
    [self.view addSubview:stackView];


    //Layout for Stack View
    [stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
    [stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}

Hinweis: Dies wurde auf iOS 9 getestet

UIStackView Gleicher Abstand (zentriert)


Beantwortet von –
user1046037


Antwort geprüft von –
Marilyn (FixError Volunteer)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

[FIXED] openURL: in iOS 10 veraltet

Ausgabe Apple mit iOS 10 ist veraltet openURL: for openURL:option:completionHandler Wenn ich: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]]; Wie wird…