32
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列の長さによりUILabelのheightが自動調整し、かつ、TableViewCellのheightもそれに合わせて自動調整する

Last updated at Posted at 2015-04-06

NOTE

Case 1) 文字列の長さによりUILabelのheightが自動調整し、かつ、TableViewCellのheightもそれに合わせて自動調整する

UILabel(UIView)

  • "Lines"をゼロに設定
  • top/left spaces and (bottom/right spaces or width/height)のConstraintsを設定
  • 最下部のUIViewのbottom space Constraintのpriorityを下げる

UITableViewCell

  • UIView.preferredMaxLayoutWidthを設定
e.g.)
- (void)layoutSubviews {
    CGRect bounds = self.bounds;
    self.messageLabel.preferredMaxLayoutWidth = bounds.size.width - 12 - 12; // horizontal spaces in Constants
    [super layoutSubviews];
}

UITableView

  • tableView:cellForRowAtIndexPath:にて、コンテンツを設定
e.g.)
TableViewCell02 *c = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell02" forIndexPath:indexPath];
[c setMessage:_message021];
cell = c;
  • tableView:heightForRowAtIndexPath:にて、[UIView systemLayoutSizeFittingSize]よりheightを取得/設定(iOS7の場合)
  • tableView:heightForRowAtIndexPath:にて、UITableViewAutomaticDimensionをheightに設定(iOS8の場合)
e.g.)
CGFloat height;
if (SYSTEM_VERSION_GREATER_THAN(@"8.0")) {
    height = UITableViewAutomaticDimension;
}
else {
    [_stubCell02 setMessage:_message021];
    [_stubCell02 setNeedsLayout];
    [_stubCell02 layoutIfNeeded];
    height = [_stubCell02.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}
  • tableView:estimatedHeightForRowAtIndexPath:にて、estimate heightを設定
e.g.)
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 43.0;
}

UIViewController

  • "Simulated Size"は、"Fixed"に設定 (Because, on iOS7, [UIView systemLayoutSizeFittingSize:] doesn't return a correct size)

Case 2) Case1にheightの最大値を設ける

UILabel(UIView)

  • HeightのConstraintsを設定

See

32
34
0

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
32
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?