33

我正在开发一个 iPhone 应用程序,我想在 UILabel 中设置字距调整。我编写的代码(可能在 附近kCTKernAttributeName)似乎有误。我该如何解决这个问题?

NSMutableAttributedString *attStr;   
NSString *str = @"aaaaaaa";    
CFStringRef kern = kCTKernAttributeName;        
NSNumber *num = [NSNumber numberWithFloat: 2.0f];    
NSDictionary *attributesDict = [NSDictionary dictionaryWithObject:num 
forKey:(NSString*)kern];        
[attStr initWithString:str attributes:attributesDict];      
CGRect frame1 = CGRectMake(0, 0, 100, 40);    
UILabel *label1 = [[UILabel alloc] initWithFrame:frame1];    
label1.text = attStr    
[self.view addSubview:label1];
4

9 回答 9

61

老问题,但你现在可以(很容易)做到。

NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Please get wider"];
[attributedString addAttribute:NSKernAttributeName value:@5 range:NSMakeRange(10, 5)];
[self.label setAttributedText:attributedString];

在此处输入图像描述

对于 2013 年 11 月,为了扩展这个很好的答案,这里有一些完全典型的代码。通常你也会设置字体。请注意评论中使用普通旧 .text 的老式方式。希望它可以帮助某人

NSString *yourText = @"whatever";

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];

// simple approach with no tracking...
// label.text = yourText;
// [label setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:24]];

NSMutableAttributedString *attributedString;

attributedString = [[NSMutableAttributedString alloc] initWithString:yourText];

[attributedString addAttribute:NSKernAttributeName
                         value:[NSNumber numberWithFloat:2.0]
                         range:NSMakeRange(0, [yourText length])];

[attributedString addAttribute:NSFontAttributeName
                         value:[UIFont fontWithName:@"HelveticaNeue-Light" size:24]
                         range:NSMakeRange(0, [yourText length])];

label.attributedText = attributedString;

label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;

[label sizeToFit];
于 2012-11-27T14:36:17.637 回答
25

前:

前

后:

咖啡馆

这是一个 Swift 3 扩展,可让您通过代码故事板设置 UILabel 的字距:

extension UILabel {

    @IBInspectable var kerning: Float {
        get {
            var range = NSMakeRange(0, (text ?? "").count)
            guard let kern = attributedText?.attribute(NSAttributedStringKey.kern, at: 0, effectiveRange: &range),
                let value = kern as? NSNumber
                else {
                    return 0
            }
            return value.floatValue
        }
        set {
            var attText:NSMutableAttributedString

            if let attributedText = attributedText {
                attText = NSMutableAttributedString(attributedString: attributedText)
            } else if let text = text {
                attText = NSMutableAttributedString(string: text)
            } else {
                attText = NSMutableAttributedString(string: "")
            }

            let range = NSMakeRange(0, attText.length)
            attText.addAttribute(NSAttributedStringKey.kern, value: NSNumber(value: newValue), range: range)
            self.attributedText = attText
        }
    }
}

演示用法:

myLabel.kerning = 3.0

或者

在此处输入图像描述

该演示使用 3.0 字距调整戏剧,但我发现0.1 - 0.8在实践中往往效果很好。

于 2016-01-13T01:45:38.770 回答
19

以 DBD 的回答,我在 UILabel 上创建了一个类别,如果在 iOS6+ 上运行,它允许设置字距调整,并优雅地回退到仅在以前的 iOS 版本上设置文本。可能对其他人有帮助...

UILabel+TextKerning.h

#import <UIKit/UIKit.h>

@interface UILabel (TextKerning)

/**
 * Set the label's text to the given string, using the given kerning value if able.
 * (i.e., if running on iOS 6.0+). The kerning value specifies the number of points
 * by which to adjust spacing between characters (positive values increase spacing,
 * negative values decrease spacing, a value of 0 is default)
 **/
- (void) setText:(NSString *)text withKerning:(CGFloat)kerning;

/**
 * Set the kerning value of the currently-set text.  The kerning value specifies the number of points
 * by which to adjust spacing between characters (positive values increase spacing,
 * negative values decrease spacing, a value of 0 is default)
 **/
- (void) setKerning:(CGFloat)kerning;

@end

UILabel+TextKerning.m

#import "UILabel+TextKerning.h"

@implementation UILabel (TextKerning)

-(void) setText:(NSString *)text withKerning:(CGFloat)kerning
{
    if ([self respondsToSelector:@selector(setAttributedText:)])
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
        [attributedString addAttribute:NSKernAttributeName
                                 value:[NSNumber numberWithFloat:kerning]
                                 range:NSMakeRange(0, [text length])];
        [self setAttributedText:attributedString];
    }
    else
        [self setText:text];
}

-(void) setKerning:(CGFloat)kerning
{
    [self setText:self.text withKerning:kerning];
}
于 2013-03-26T00:33:03.507 回答
6

为了在这里保持最新状态,iOS 6 为UILabel和引入了属性文本UITextView

UILabel 参考:http:
//developer.apple.com/library/ios/#documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/attributedText

于 2012-11-13T14:39:33.757 回答
5

只需在 Swift 中执行此操作:

    let myTitle = "my title"
    let titleLabel = UILabel()
    let attributes: NSDictionary = [
        NSFontAttributeName:UIFont(name: "HelveticaNeue-Light", size: 20),
        NSForegroundColorAttributeName:UIColor.whiteColor(),
        NSKernAttributeName:CGFloat(2.0)
    ]
    let attributedTitle = NSAttributedString(string: myTitle, attributes: attributes as? [String : AnyObject])

    titleLabel.attributedText = attributedTitle
    titleLabel.sizeToFit()
于 2015-11-17T00:23:49.497 回答
3

使用 IBDesignables 和 IBInspectables 的示例,您可以在其中仅通过情节提要设置字距调整值。我发现它非常实用,我想与您分享。

UILabelKerning.h

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface UILabelKerning : UILabel
@property (assign, nonatomic) IBInspectable int kerning;
@end

UILabelKerning.m

#import "UILabelKerning.h"

@implementation UILabelKerning


-(void)awakeFromNib {

    [self setTheAttributes];
}

- (id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        // Initialization code
    }

    return self;
}
-(void)setTheAttributes{
    NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedString addAttribute:NSKernAttributeName
                             value:[NSNumber numberWithFloat:self.kerning]
                             range:NSMakeRange(0, [self.text length])];
    [self setAttributedText:attributedString];
}
@end

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

于 2016-02-02T14:36:05.070 回答
1

据我所知,UILabel不会渲染NSAttributedString. 有几个不错的开源解决方案。我最近使用TTTAttributedLabel作为交换来替代接受 NSAttributedString 的 UILabel。

DTCoreText(以前的 NSAttributedString+HTML)最近也受到了一些关注。

于 2011-09-10T08:35:12.147 回答
1

斯威夫特 4 和 5

extension NSAttributedString {

    /// Returns a new instance of NSAttributedString with same contents and attributes with kerning added.
    /// - Parameter kerning: a kerning you want to assign to the text.
    /// - Returns: a new instance of NSAttributedString with given kerning.
    func withKerning(_ kerning: CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(attributedString: self)
        attributedString.addAttributes([.kern: kerning],
                                       range: NSRange(location: 0, length: string.count))
        return NSAttributedString(attributedString: attributedString)
    }
 ]
于 2020-05-10T07:23:23.937 回答
-1

在斯威夫特 2.0...

添加扩展:

extension UIView {
    func attributes(font: String, color: UIColor, fontSize: CGFloat, kern: Double) -> [String: NSObject] {
        let attribute = [
            NSForegroundColorAttributeName: color,
            NSKernAttributeName: kern,
            NSFontAttributeName : UIFont(name: font, size: fontSize)!
        ]
        return attribute
    }
}

现在,只需将您的 UILabel 设置为属性文本:

self.label.attributedText = NSMutableAttributedString(string: "SwiftExample", attributes: attributes("SourceSans-Regular", color: UIColor.whiteColor(), fontSize: 20, kern: 2.0))   

显然,我添加了一堆你可能不需要的参数。玩转——随意重写方法——我在一堆不同的答案上寻找这个,所以我想我会发布整个扩展,以防它帮助那里的人......-rab

于 2016-03-16T08:24:52.587 回答