UIViewクラスは、画面上の矩形領域と領域内のコンテンツを管理するクラスです。領域内のコンテンツの描画を処理し、またコンテンツとのインターフェースを処理します。
 

Objective-C
Xcode 9.4
Xcode 9.4
UIView
UIView はGUIを作る上で基本的なもので、以下ような処理を管理しています。
- 描画とアニメーション
- レイアウトとサブビューの管理
- イベントのハンドリング
インスタンス生成
矩形領域を指定してインスタンス生成。例として、x,yの始点が0で横幅が100、縦幅が200の矩形は以下のような設定です。
 
| 1 2 | CGRect viewRect = CGRectMake(0, 0, 100, 200); UIView* testView = [[UIView alloc] initWithFrame:viewRect]; | 
 
インスタンスの生成してから矩形領域を設定する場合はframeを使います。
 
| 1 2 3 4 | UIView *testView = [[UIView alloc] init]; CGRect testViewRect = CGRectMake(0, 0, 100, 200); testView.frame = testViewRect; | 
メソッド
主なメソッドは
- – (void)addSubview: (UIView *)view
- サブビューを追加
 
- – (void)drawRect: (CGRect)rect
- 図形を描画
 
- – (void)sizeToFit
- コンテンツが入るようにUIViewをリサイズ、移動する
 
プロパティ
| frame | ビューの位置とサイズを表すフレーム矩形 | 
| center | 中心位置を指定 | 
| backgroundColor | 背景色を指定 | 
| hidden | 表示、非表示を指定 | 
| bounds | 独自の座標系でビューの位置とサイズを表す境界の矩形 frame はsuperviewからみた矩形サイズで bounds はそれ自身のサイズで回転されても変わらない | 
サンプルコード
UIViewのインスタンスを生成して背景色を変え
その中にUIImageViewを置いてみます。
 
ViewController.m
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {     [super viewDidLoad];     // スクリーンサイズを取得     CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;     CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;     // UIView インスタンス作成     UIView *testView = [[UIView alloc] init];     // 矩形を作成     CGFloat testViewWidth = screenWidth-20;     CGFloat testViewHieght = screenHeight-80;     CGRect testViewRect = CGRectMake(10, 40, testViewWidth, testViewHieght);     // testView のサイズとする     testView.frame = testViewRect;     // testView の背景色を設定     testView.backgroundColor = [UIColor lightGrayColor];     UIColor *customColor = [UIColor colorWithRed:0.75 green:0.9 blue:0.85 alpha:1.0];     testView.backgroundColor = customColor;     // UIImageView インスタンスの作成     UIImage *image = [UIImage imageNamed:@"sample@2x.jpg"];     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];     // 画像の中心をtestViewの中心に設定     [imageView setCenter:CGPointMake(testViewWidth/2, testViewHieght/2)];     // testView に imageView を追加     [testView addSubview:imageView];     // testView をviewに追加     [self.view addSubview:testView];     // 非表示     //testView.hidden = YES;     // 表示     testView.hidden = NO; } - (void)didReceiveMemoryWarning {     [super didReceiveMemoryWarning];     // Dispose of any resources that can be recreated. } @end | 
 
実行してViewが表示されているのを確認してください。
 

 
画像をtestViewの上に追加するのですが、位置調整は当然ですがtestViewの位置に合わせないとおかしくなります。どうぜ画面の中央ということでscreenWidth/2, screenHeight/2で設定するとずれてしまいます。
 
| 1 2 3 4 5 | // 画像の中心をtestViewの中心に設定 [imageView setCenter:CGPointMake(testViewWidth/2, testViewHieght/2)]; // testView に imageView を追加 [testView addSubview:imageView]; |