Ich erstelle eine App in> = iOS6. Und ich möchte den Zeichenabstand in UILabel ändern. Ich habe in meiner App die benutzerdefinierte Schriftart "FUTURABT HEAVY" hinzugefügt, aber der Charakter ist zu nahe beieinander.
Ich habe den guten Code hier gefunden, um den Zeichenabstand zu vergrößern. Wenn ich es jedoch ändern wollte, wurde mein Text anstelle der Mitte linksbündig.
Bitte helfen Sie mir in dieser Situation.
Sie sollten wahrscheinlich NSAttributedString
mit dem Attribut NSKernAttributeName
verwenden
Hier ist ein kleines Beispiel:
UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
NSString *string = @"Some important text";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
float spacing = 5.0f;
[attributedString addAttribute:NSKernAttributeName
value:@(spacing)
range:NSMakeRange(0, [string length])];
label.attributedText = attributedString;
[self.view addSubview:label];
Schnelle Erweiterung für diese
extension UILabel {
func addCharactersSpacing(spacing:CGFloat, text:String) {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSMakeRange(0, text.characters.count))
self.attributedText = attributedString
}
}
So kannst du es benutzen
MyLabel.addCharactersSpacing(5, text: "Some Text")
Swift 4
extension UILabel {
func setCharacterSpacing(characterSpacing: CGFloat = 0.0) {
guard let labelText = text else { return }
let attributedString: NSMutableAttributedString
if let labelAttributedText = attributedText {
attributedString = NSMutableAttributedString(attributedString: labelAttributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Character spacing attribute
attributedString.addAttribute(NSAttributedStringKey.kern, value: characterSpacing, range: NSMakeRange(0, attributedString.length))
attributedText = attributedString
}
}
Swift 3
let label = UILabel()
let stringValue = "Sample text"
let attrString = NSMutableAttributedString(string: stringValue)
attrString.addAttribute(NSKernAttributeName, 2: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
NSString *strDigit= @"001";
NSString *strCrushImpact =[NSStringstringWithFormat:@"%d",[strDigit intValue]];
// Set space in between character
float spacing = 3.0f;
NSMutableAttributedString *attributedStrDigit = [[NSMutableAttributedString alloc] initWithString:strWin];
[strCrushImpact addAttribute:NSKernAttributeName value:@(spacing)
range:NSMakeRange(0, [strDigit length])];
label.attributedText = attributedStrDigit;