簡體   English   中英

如何更改 UILabel 中的字母間距?

[英]How do I change the letter spacing in a UILabel?

我想更改UIKit UILabel數字之間的間距,使其相等。

使用標准間距,標簽如下所示:

字符間距不均勻的標簽

我希望它看起來像這樣:

具有均勻字符間距的標簽

如何做到這一點?

您可以在屬性字符串上使用NSKernAttributeName屬性:

UILabel *label = [UILabel new];

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] 
                                   initWithString:@"127"];

// The value paramenter defines your spacing amount, and range is 
// the range of characters in your string the spacing will apply to. 
// Here we want it to apply to the whole string so we take it from 0 to text.length.
[text addAttribute:NSKernAttributeName 
             value:@-0.5 
             range:NSMakeRange(0, text.length)];

[label setAttributedText:text];

最簡單的方法是創建一個自定義 UILabel 類並從 Storyboard 設置字母間距。

open class CustomLabel : UILabel {
    @IBInspectable open var characterSpacing:CGFloat = 1 {
        didSet {
            let attributedString = NSMutableAttributedString(string: self.text!)
            attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
            self.attributedText = attributedString
        }

    }
}

在此處輸入圖片說明

在快速實施看起來像

let text = "TIPS, ARTICLES & BEST OFFERS"
label.attributedText = NSAttributedString(string: text, attributes: [.kern: 3.12])

NSAttributedString .kern 屬性

您可以使用 NSAttributedString 並使用 NSKernAttributeName 屬性。 默認值為 0,因此您需要將其設置為負數。

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/#//apple_ref/doc/constant_group/Character_Attributes

在 Obj-C 中,您可以執行以下操作:

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString: @"Test test test test "];
[attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)];

label.attributedText = attrStr;

在 Swift 中,您可以執行以下操作:

let myTitle = "my title"
let titleLabel = UILabel()
let attributes: NSDictionary = [
    NSFontAttributeName:UIFont(name: "FONT_NAME", size: TEXT_SIZE),
    NSKernAttributeName:CGFloat(2.0)
]

let attributedTitle = NSAttributedString(string: myTitle, attributes:attributes as? [String : AnyObject])

titleLabel.attributedText = attributedTitle

可以使用NSKernAttributeName

但更正其他答案:不適用於全文長度,但(text.length - 1)

將負或正間距添加到字母中,最后一個不需要。 假設您要添加一個正間距,它會在最后一個字母之后的間距中結束。 居中的字符串似乎不再居中。 這同樣適用於負間距。

NSString *text = @"Sample Text";    
UILabel *label = [UILabel new]

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: text];
[attributedString addAttribute:NSKernAttributeName value:[NSNumber numberWithDouble:-1.0] range:NSMakeRange(0, text.length-1)];

[label setAttributedTitle:attributedString forState:UIControlStateNormal];

應用於全文長度。

應用於全文長度。

應用於(文本長度 - 1)。 應用於(文本長度 - 1)。

我從@J2K 那里得到了答案,並將其翻譯成Swift 4.2擴展。

/// Set the text of the label but altering the kerning so that you can control the space between each characters.
///
/// - Parameters:
///   - text: New content of the label
///   - kerning: Set a value between 0 and 1 to lower the space between characters. Above 0, spacing will be increased. 0 disables kerning.
extension UILabel {

    func set(text: String, withKerning kerning: CGFloat) {
        let attributedString = NSMutableAttributedString(string: text)

        // The value parameter defines your spacing amount, and range is
        // the range of characters in your string the spacing will apply to.
        // Here we want it to apply to the whole string so we take it from 0 to text.count.
        attributedString.addAttribute(NSAttributedString.Key.kern, value: kerning, range: NSMakeRange(0, text.count))

        attributedText = attributedString
    }

}

如果要將字母間距屬性應用於 Interface Builder 中的所有 UILabels 而不修改任何內容(對於特定字體):

斯威夫特 4:

/**
 * Applies letter spacing to selected fonts in UILabels from IB.
 *
 * - author Alexander Volkov
 * - version 1.0
 */
extension UILabel {

    /// Applies letter spacing
    open override func awakeFromNib() {
        super.awakeFromNib()
        applyLetterSpacing()
    }

    /// Applies letter spacing
    ///
    /// - Parameter aDecoder: the decoder
    /// - Returns: UILabel instance
    open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
        let label = super.awakeAfter(using: aDecoder)
        self.applyLetterSpacing()
        return label
    }


    /// Applies letter spacing
    func applyLetterSpacing() {
        if font.fontName.contains("Oswald", caseSensitive: false) {
            let characterSpacing: CGFloat = 1
            let string = NSMutableAttributedString(string: self.text!)
            string.addAttribute(.kern, value: characterSpacing, range: NSRange(location: 0, length: string.length - 1))
            self.attributedText = string
        }
    }
}
NSString *myString = @"127";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:myString];

float letterSpacing = -1.50f; // change spacing here
[attributedString addAttribute:NSKernAttributeName value:@(letterSpacing) range:NSMakeRange(0, [myString length])];
[myLabel setAttributedText:attributedString];

另請參閱此以獲取更多信息和結果: http : //www.devsign.co/notes/tracking-and-character-spacing

試試這個。 它將添加您指定的字符間距,您可以設置簡單文本或屬性文本。 https://stackoverflow.com/a/49929848/4559803

我發現這是最好的解決方案。 它還包括 UIButton,應用可能已在界面構建器中設置的屬性並適應不同的字體:

extension UILabel {

    open override func awakeFromNib() {
        super.awakeFromNib()
        applyLetterSpacing()
    }

    func applyLetterSpacing() {
        // return if empty text
        if((text ?? "").isEmpty) {
            return
        }

        // default spacing
        var spacing = 1
        if(font.familyName == "Source Serif Pro") {
            // custom spacing for different font
            spacing = 2
        }
        var attributes = attributedText?.attributes(at: 0, effectiveRange: nil) ?? [:]
        attributes[.kern] = spacing
        attributedText = NSAttributedString(string: text ?? "", attributes: attributes)
    }

}

和按鈕

extension UIButton {

    open override func awakeFromNib() {
        super.awakeFromNib()
        applyLetterSpacing()
    }

    func applyLetterSpacing() {
        if((title(for: .normal) ?? "").isEmpty) {
            return
        }
        var attributes = attributedTitle(for: .normal)?.attributes(at: 0,     effectiveRange: nil) ?? [:]
        attributes[.kern] = 1
        attributes[.foregroundColor] = titleColor(for: .normal)
        setAttributedTitle(NSAttributedString(string: title(for: .normal) ?? "", attributes: attributes), for: .normal)
    }
}

單擊標簽並轉到您的屬性檢查器。 將文本從純文本更改為屬性文本。 您將有幾個間距選項。 希望這會有所幫助。

暫無
暫無

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

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