LoginSignup
35
35

More than 5 years have passed since last update.

[Objective-C] UIViewをいい感じに上下左右センタリングする

Posted at

いやーレイアウト大変ですね。HTMLのレイアウト能力の高さを実感する毎日です。
本当はAuto Layoutとか使えば解決するんだと思うんですが、現状の案件ではそれが使えないので色々試行錯誤中です。
(なのでこうやったら楽だゼ、ってことを知っていたら教えてください( ;´Д`))

今回は内包する要素にフィットさせつつ、それを上下左右にセンタリングするのをメモしておきます。

// ベースのビュー(これをセンタリングする)
UIView *baseView = [[UIView alloc] init];
[baseView addSubview:label];


// アイコンビュー
UIImage image = [UIImage imageNamed:@"hoge"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[baseView addSubview:imageView];


// アイコンのラベル
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame), 0, 0)];
label.text = @"test";
[baseView addSubview:label];
[label sizeToFit]; // テキストにフィットさせる

// アイコン+テキストの領域を内包するCGRectを生成
baseView.frame  = CGRectUnion(label.frame, imageView.frame);
baseView.center = CGPointMake(self.view.bounds.width / 2, self.view.bounds.height / 2);
imageView.center = CGPointMake(baseView.bounds.width / 2, imageView.bounds.size.height / 2);

ポイント

ポイントは、CGRectUnionを使って、内包している要素の領域を結合したCGRectを生成している点です。
これで内包している要素にフィットするようになります。
サイズ変更後、改めて内部の要素をセンタリングして、最終的にアイコン+テキストをセンタリングしつつ、画面中央にビューを配置する、という手順です。

35
35
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
35