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
藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事