【问题标题】:Xcode UILabel bug? Line spacing cropping text with a UILabelXcode UILabel 错误?使用 UILabel 裁剪文本的行距
【发布时间】:2018-08-30 19:13:58
【问题描述】:

我正在为一个 iOS 项目设计一些设计。使用的字体是 Avenir,行距相对紧凑。

其中一些标签会有动态文本,所以我不能只将标签的尺寸变大,因为尺寸应该由内容决定。

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

如果我调整Line Height MultipleMax Height,顶部的文本最终会被裁剪。


它的行为应该是这样的(Affinity Designer)...

有没有办法解决这个问题?

感谢您的帮助!

【问题讨论】:

    标签: ios xcode uilabel interface-builder


    【解决方案1】:

    不幸的是,UILabel 在垂直调整方面有几个怪癖。一个有点老套的解决方案是根据需要将第一行的基线向下移动。根据您的字符串是否以换行符结尾,以及您执行的收紧量,您可能还需要添加一到两个额外的换行符,否则渲染引擎将剪切最后一行。

    代码 sn-p 假定 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;
    

    【讨论】:

      【解决方案2】:

      这对我有用。通过添加

      最小线高

      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
      

      【讨论】:

        猜你喜欢
        • 2018-08-24
        • 2012-10-06
        • 1970-01-01
        • 2016-03-03
        • 1970-01-01
        • 2015-08-03
        • 2011-03-29
        • 1970-01-01
        • 2015-11-24
        相关资源
        最近更新 更多