Xcode UILabel错误?行间距裁剪文本与UILabel

时间:2018-03-21 15:20:00

标签: ios xcode uilabel interface-builder

我有一些关于iOS项目的设计。使用的字体是Avenir,行距相对较窄。

其中一些标签会包含动态文字,因此我不能仅仅将标签的尺寸设置得更大,因为尺寸应由内容决定。

默认情况下,UILabel的行间距非常大。

Default Line Spacing

如果我调整Line Height MultipleMax Height,则顶部的文字会被裁剪。 Height Multiple

enter image description here

它应该像这样(Affinity Designer)...... enter image description here

有办法解决这个问题吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

这对我有用。通过添加

minimumLineHeight

let string = NSMutableAttributedString(string: venue.name)
let style = NSMutableParagraphStyle()
style.lineHeightMultiple = 0.68
style.minimumLineHeight = nameLabel.font.lineHeight
string.addAttribute(NSAttributedString.Key.paragraphStyle,
                    value: style,
                    range: NSMakeRange(0, venue.name.count))
nameLabel.attributedText = string

答案 1 :(得分:0)

不幸的是,UILabel在垂直调整方面有几个怪癖。一个有点hacky的解决方案是根据需要将第一行的基线向下移动。根据你的字符串是否以换行符结束,以及你所做的紧缩程度,你可能还需要添加一个或两个额外的换行符,否则渲染引擎将剪切最后一行。

代码段假定self.label已经为其分配了属性字符串,并且行之间有行分隔符0x2028。在IB中输入多行文本时通常会这样。

// 0x2028 is the unicode line separator character
// Use \n instead if it is what you have
// or calculate the length of the first line in some other way
NSInteger lengthOfFirstLine = [self.label.text componentsSeparatedByString:@"\u2028"][0].length;
NSMutableAttributedString *s = [[NSMutableAttributedString alloc] initWithAttributedString:self.label.attributedText];

// Add two more blank lines so that the rendering engine doesn't clip the last line
[s appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n\n"]];

// Move the baseline offset for the first line down
// the other lines will adjust to this
// 50 is a value you will have to find what looks best for you
[s addAttribute:NSBaselineOffsetAttributeName value:@(-50) range:NSMakeRange(0, lengthOfFirstLine)];
self.label.attributedText = s;