在uistackview中以编程方式更改视图高度

时间:2018-08-20 09:35:44

标签: ios objective-c uistackview

按下测试按钮时,我需要在堆栈视图中更改视图高度,但是它不能正常工作。

当我按下测试按钮时,我想将视图3的高度设置为50,将视图5的高度设置为填充剩余区域。当我再次按下测试按钮时,我想返回到过程。我该怎么办?

谢谢。

enter image description here

1 个答案:

答案 0 :(得分:0)

正如@ SeanLintern88所述,您真正应该这样做的方法是使用自动布局约束-您不想将setFrame与autolayout混合使用。

IBOutlet View 3和View 5的高度约束。将View 3高度约束设置为非活动状态以启动(如果您希望它看起来像故事板当前正在启动),则每当按下按钮时,检查哪个约束处于活动状态并将其触发器。

StackView_View_Resize

#import "ViewController.h"

@interface ViewController ()
@property (strong, nullable) IBOutlet NSLayoutConstraint *view3HeightConstraint;
@property (strong, nullable) IBOutlet NSLayoutConstraint *view5HeightConstraint;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // start us out as inactive
    self.view3HeightConstraint.active = NO;
}

- (IBAction)btnPressed:(id)sender {
    if (self.view5HeightConstraint.active) {
        // view 5 height constraint is active
        // you can set the height constants directly in storyboard as well
        self.view3HeightConstraint.constant = 50.0f;
        self.view3HeightConstraint.active = YES;
        self.view5HeightConstraint.active = NO;
    } else {
        // view 3 is height constraint is active
        // you can set the height constants directly in storyboard as well
        self.view5HeightConstraint.constant = 50.0f;
        self.view5HeightConstraint.active = YES;
        self.view3HeightConstraint.active = NO;
    }
    // animate the layoutIfNeeded so we can get a smooth animation transition
    [UIView animateWithDuration:1.0f animations:^{
        [self.view layoutIfNeeded];
    }];
}


@end