如何将填充添加到NSMutableAttributedString?

问题描述 投票:2回答:2

我有一个标签使用NSMutableAttributedString写出文本:

enter image description here

我想要做的是降低星号的顶部填充,以便它的midY甚至是下面的“烹饪”这个词:

enter image description here

如何使用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
}()
ios swift uilabel padding nsmutableattributedstring
2个回答
3
投票

baselineOffset属性键用于此目的。

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

enter image description here

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

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

enter image description here


1
投票

正如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

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

© www.soinside.com 2019 - 2024. All rights reserved.