IOS

iOS Method for Setting Line Spacing of UILabel and Adapting Height


Examples are as follows:

NSString *contentStr = @" Always thought , In the original place , Have 1 The original me , There will be 1 The original you ";

  UILabel *tempLabel = [[UILabel alloc] init];
  // Set the background color
  tempLabel.backgroundColor = [UIColor redColor];
  // Setting content
  tempLabel.text = contentStr;
  // Set the font color
  tempLabel.textColor = [UIColor whiteColor];
  // Set the font size
  tempLabel.font = [UIFont systemFontOfSize:15.0];
  // Set whether the text is displayed in multiple lines
  tempLabel.numberOfLines = 0;
  tempLabel.lineBreakMode = NSLineBreakByWordWrapping;
  // Settings UILabel Adapt height according to text
  CGSize size = [tempLabel sizeThatFits:CGSizeMake(100, MAXFLOAT)];
  // Settings frame
  tempLabel.frame = CGRectMake(50, 100, 100, size.height);
  [self.view addSubview:tempLabel];
  // Settings label Line spacing of
  NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentStr];
  NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  [paragraphStyle setLineSpacing:8];
  [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [contentStr length])];
  [tempLabel setAttributedText:attributedString];
  [tempLabel sizeToFit];