如何向 NSMutableAttributedString 添加填充?

How to add padding to a NSMutableAttributedString?

我有一个标签,它使用 NSMutableAttributedString 将文本写为:

我想要做的是降低星号的顶部填充,使其中间与 Cuisine 一词齐平,如下所示:

如何使用 NSMutableAttributedString 添加填充?

我知道我可以单独使用星号创建一个单独的标签,并使用带常量的锚点将其居中,但我想看看如何使用 NSMutableAttributedString

let cuisineLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false

    let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.lightGray])

    attributedText.append(NSAttributedString(string: "*", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24), NSAttributedStringKey.foregroundColor: UIColor.red]))

    label.attributedText = attributedText

    return label
}()

正如 Code Different 指出的那样,您可以使用 baselineOffset 属性来做到这一点。 -8 的值应该适用于您的情况:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        self.view = view

        let cuisineLabel: UILabel = {
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [
                NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17),
                NSAttributedStringKey.foregroundColor: UIColor.lightGray])

            attributedText.append(NSAttributedString(string: "*", attributes: [
                NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24),
                NSAttributedStringKey.baselineOffset: -8,
                NSAttributedStringKey.foregroundColor: UIColor.red]))

            label.attributedText = attributedText

            return label
        }()

        view.addSubview(cuisineLabel)

    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

如果由于新基线而导致行高偏移混乱,并且您正在使用多行标签,请尝试使用 lineHeightMultiple:

let lineStyle = NSParagraphStyle()
lineStyle.lineHeightMultiple = 0.8

...

NSAttributedStringKey.paragraphStyle = style

如果不是(并且您使用的是多个标签堆叠在一起),那么您可能只需要调整系列中每个标签的框架即可进行补偿。

baselineOffset 属性键用于此目的。

let cuisine = NSMutableAttributedString(string: "Cuisine")
let asterisk = NSAttributedString(string: "*", attributes: [.baselineOffset: -3])
cuisine.append(asterisk)

显然,您必须使用其余文本的字体大小来计算偏移量。这就是为什么我认为使用全角星号 (*) 更容易。

带有全角星号的结果(您可能希望其字体大小与字符串其余部分的字体大小成比例):