如何将 NSMutableAttributedString 设置成两行

How to set NSMutableAttributedString into two lines

我想像这样创建一个 UILablel

我想将年份字体设置为 HEvaticaNeu-medium,将 2015 设置为 HelvaticaNeu。我需要这两个字符串出现在 2 行中,就像这个图像中一样。

我该怎么做。我以这种方式设置了两个单独的NSMutableAttributedString

UIFont *helMedium = [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:@"Year :" attributes: mediumDict];

UIFont *helNormal = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"2016" attributes: normalDict];

现在我应该如何将这两个字符串设置成两行? 有人有想法吗?

NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"\n2016" attributes: normalDict];

NSMutableAttributedString  *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString: mAttrString];
[attString appendAttributedString: nAttrString];

// label.attributedText = attString

您需要将第二个字符串附加到第一个字符串

使用此代码。

UIFont *helMedium = [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0];
NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:@"Year :" attributes: mediumDict];

UIFont *helNormal = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"\n2016" attributes: normalDict];

[mAttrString appendAttributedString:nAttrString];

label.attributedText = mAttrString;
  UIFont *helMedium = [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0];
  NSDictionary *mediumDict = [NSDictionary dictionaryWithObject: helMedium forKey:NSFontAttributeName];
  NSMutableAttributedString *mAttrString = [[NSMutableAttributedString alloc] initWithString:@"Year :" attributes: mediumDict];

  UIFont *helNormal = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
  NSDictionary *normalDict = [NSDictionary dictionaryWithObject: helNormal forKey:NSFontAttributeName];
  NSMutableAttributedString *nAttrString = [[NSMutableAttributedString alloc] initWithString:@"\n2016" attributes: normalDict];

  [mAttrString appendAttributedString:nAttrString];
  _yearLabel.attributedText = mAttrString;
  [_yearLabel setNumberOfLines:2];

如果您想要 space UILabel 中文本周围的更多内容,请为其指定宽度和高度限制。