如何向 NSMutableAttributedString 添加填充?

Lan*_*ria 5 padding uilabel ios nsmutableattributedstring swift

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

在此处输入图片说明

我想要做的是降低星号的顶部填充,以便它的 midY 与下面的 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
}()
Run Code Online (Sandbox Code Playgroud)

bra*_*ipt 5

正如 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()
Run Code Online (Sandbox Code Playgroud)

如果您正在努力解决因新基线而导致行高偏移混乱的问题,并且您正在使用多行标签,请尝试使用lineHeightMultiple

let lineStyle = NSParagraphStyle()
lineStyle.lineHeightMultiple = 0.8

...

NSAttributedStringKey.paragraphStyle = style
Run Code Online (Sandbox Code Playgroud)

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


Swe*_*per 5

baselineOffset属性键用于此目的。

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

在此处输入图片说明

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

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

在此处输入图片说明