UILabelを上寄せにする方法(簡易版)
UILabelを上寄せにしたい場合がある。
その場合、OHAttributedLabelやTTTAttributedLabelなど便利なライブラリがあるけど、ただ単に上寄せしたいだけならばUILabelの高さを適切なサイズに変更してあげれば上寄せになる。(上寄せというか高さを文字が入るぎりぎりに調整するだけだが)
やり方
- (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です。