UIView の真ん中に文字を表示する方法のメモです。

(iOS5で試してます。)

UILabel を うまく真ん中に持っていくために、

・CGRectZero:サイズ、位置は後で決めるときに便利なゼロの四角

・sizeToFit:フォントサイズに合わせてサイズを自動調整

・center:センターの座標を指定

などを使っていきます。

赤い四角の真ん中に、ひらがなの「あ」を表示するサンプルを書いていきます。

サンプルコード

(※ ViewController.m に実装して試しました)

– (void)viewDidLoad

{

    [superviewDidLoad];

    

    

    // 四角を表示

    UIView *v = [[UIViewalloc] initWithFrame:CGRectMake(20, 20, 50, 50)];

    v.backgroundColor = [UIColorredColor];

    [self.view addSubview:v];

    

    

    // ラベル

    UILabel *label = [[UILabelalloc] initWithFrame:CGRectZero];

    label.backgroundColor = [UIColorclearColor];

    label.font = [UIFont systemFontOfSize:30];

    label.text = @”;

    

    // ラベルのFrameを調整

    [label sizeToFit];

    

    // 真ん中を指定 

    // convertPoint 座標を、ラベルを貼付けるViewnのローカル座標に変更

    label.center = [self.view convertPoint:v.center toView:v];

    

    [v addSubview:label];

}