iOS - 在运行时调整UIScrollView内容的大小

时间:2014-04-09 17:17:06

标签: ios objective-c uiscrollview autolayout

我有一个如下所示的视图:

View screenshot

红色矩形(引用outlet:self.redView)放在scrollview(引用outlet:self.scrollView)中。当"更大"或者"较小的"按下按钮,红色矩形扩展/收缩其高度。

我的代码在这里:

#import "s1cViewController.h"

@interface s1cViewController ()

@end

@implementation s1cViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidLayoutSubviews {
    [self.scrollView setScrollEnabled:YES];
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, 600)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnBiggerTouched:(id)sender {
    [self resizeViewHeight:20];
}

- (IBAction)btnSmallerTouched:(id)sender {
    [self resizeViewHeight:-20];
}

- (void)resizeViewHeight:(int)heightDelta {
    [UIView animateWithDuration:0.2f animations:^{
        // Resize scrollview height
        /*self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.scrollView.contentSize.height + deltaInputWrapperHeight);*/

        // Resize categoryInputView height
        CGRect rect = self.redView.frame;
        rect.size.height += heightDelta;
        self.redView.frame = rect;
    }];
}

@end

当我更改矩形的高度,然后滚动时,高度会变回原始大小。我该如何防止这种情况?

1 个答案:

答案 0 :(得分:2)

也许您正在使用自动布局。如果是这样,那就是问题所在。你无法直接在自动布局下更改视图的框架,因为如果你这样做,当布局出现时,它会立即改变它(就像这里似乎发生的那样)。你必须改变约束。