我正在开发一个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];

最佳答案

旧问题,但是您现在可以(轻松)进行。

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];

关于ios - 如何在iPhone UILabel中设置字距调整,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7370013/

10-10 20:29