簡體   English   中英

如何將填充添加到NSMutableAttributedString?

[英]How to add padding to a NSMutableAttributedString?

我有一個標簽,使用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
}()

baselineOffset屬性鍵用於此目的。

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

在此處輸入圖片說明

顯然,您將必須使用其余文本的字體大小來計算偏移量。 這就是為什么我認為使用全角星號(*)更容易的原因。

具有全角星號的結果(您可能希望其字體大小與其余字符串的字體大小成比例):

在此處輸入圖片說明

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

如果不是這樣(並且您正在使用多個彼此疊放的標簽),則可能只需要調整系列中每個標簽的框架即可進行補償。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM