【问题标题】:How to adjust the baseline shift for a UiLabel?如何调整 UiLabel 的基线偏移?
【发布时间】:2015-09-13 08:07:18
【问题描述】:

我的应用正在使用自定义字体来显示整个应用的信息。

但他们的基线存在一些问题,如下图所示:

我需要将“X 4”固定在垂直红色框的中心。

我该如何解决这个问题?

【问题讨论】:

    标签: ios swift cocoa-touch uilabel


    【解决方案1】:

    您可以创建一个UILabel 并将其大小设置为与红色框相同。然后将其文本对齐设置为中心:

    youLabel.textAlignment = NSTextAlignment.Center
    

    另一个不太好的选择是制作一个与红色框大小相同的UIButton,并将其UserInteractionEnabled 设置为No。这样,您的文本将水平和垂直定位在中心。你也可以设置为setContentVerticalAlignment属性

    【讨论】:

    • 这仅适用于水平对齐,但不适用于垂直。
    • 再次检查答案。编辑它
    【解决方案2】:

    使用调整后的基线偏移设置属性字符串,就像在 Swift 中一样:

    let sttrStr = NSAttributedString.init(string: "your text",
                                          attributes:[NSAttributedStringKey.baselineOffset: -10])
    textLabel.attributedText = attrStr
    

    或在 ObjC 中类似:

    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"your string"
                                  attributes:@{ NSBaselineOffsetAttributeName : @-10 }];
    textLabel.attributedText = attrStr;
    

    按 SO 回答 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多