hachinoBlog

hachinobuのエンジニアライフ

UILabelを上寄せにする方法(簡易版)

UILabelを上寄せにしたい場合がある。

その場合、OHAttributedLabelTTTAttributedLabelなど便利なライブラリがあるけど、ただ単に上寄せしたいだけならばUILabelの高さを適切なサイズに変更してあげれば上寄せになる。(上寄せというか高さを文字が入るぎりぎりに調整するだけだが)

f:id:hachinobu:20140114212724p:plainf:id:hachinobu:20140114212734p:plain

やり方

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //Labelの設定
    self.topAlignmentLabel.backgroundColor = [UIColor yellowColor];
    self.topAlignmentLabel.numberOfLines = 0;
    self.topAlignmentLabel.text = @"abcdefghijklmnopq";
    [self setupTopAlignment];
}

- (void)setupTopAlignment
{
    //上寄せになるように高さをsizeToFitで調整する(幅は変えないため保持しておく)
    CGRect rect = _topAlignmentLabel.frame;
    [_topAlignmentLabel sizeToFit];
    rect.size.height = CGRectGetHeight(self.topAlignmentLabel.frame);
    self.topAlignmentLabel.frame = rect;
}

@end

これだけ。

ちなみにautolayoutはOFFです。