UIScrollViewをAutoLayoutで書いてみる – Objective-C

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

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


UIScrollView *redView = [[UIScrollView alloc] init];
redView.backgroundColor = [UIColor redColor];
redView.translatesAutoresizingMaskIntoConstraints = NO;
redView.contentSize = CGSizeMake(500, 500);
[self.view addSubview:redView];

// スクロールさせるViewを作成
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
view.backgroundColor = [UIColor whiteColor];
[redView addSubview:view];


NSLayoutConstraint *redLeftConstraint = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0];

NSLayoutConstraint *redBottomConstraint = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0];

NSLayoutConstraint *redWidthConstraint = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:1
constant:0];

NSLayoutConstraint *redHeightConstraint = [NSLayoutConstraint constraintWithItem:redView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.3
constant:0];

[self.view addConstraints:@[redLeftConstraint, redBottomConstraint, redWidthConstraint, redHeightConstraint]];

}

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