2016-06-15 5 views
0

UILabelの文字間隔をどのように増やして、私が行っているAppsのUIデザイン実装をより魅力的にするかを探していました。そして、私はanswer, which tells it allows to adjust the Text Kerningの後に見つかりました。Swiftで書かれています。iOS/Objecitve-C UILabelテキストカーニング

しかし、私が必要としたのはObjective-Cソリューションです。
KerningLabel.h:

#import <UIKit/UIKit.h> 
IB_DESIGNABLE 
@interface KerningLabel : UILabel 
@property (nonatomic) IBInspectable CGFloat kerning; 
@end 

KerningLabel.m:

#import "KerningLabel.h" 

@implementation KerningLabel 
@synthesize kerning; 
- (void) setAttributedText:(NSAttributedString *)attributedText { 
    if ([self.attributedText length] > 0) { 
     NSMutableAttributedString *muAttrString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText]; 
     [muAttrString addAttribute:NSKernAttributeName value:@(self.kerning) range:NSMakeRange(0, [self.attributedText length])]; 
     self.attributedText = muAttrString; 
    } 
} 
@end 
Objective-Cで次のように

import UIKit 
@IBDesignable 
class KerningLabel: UILabel { 
    @IBInspectable var kerning:CGFloat = 0.0{ 
     didSet{ 
      if ((self.attributedText?.length) != nil) 
      { 
       let attribString = NSMutableAttributedString(attributedString: self.attributedText!) 
       attribString.addAttributes([NSKernAttributeName:kerning], range:NSMakeRange(0, self.attributedText!.length)) 
       self.attributedText = attribString 
      } 
     } 
    } 
} 

:だから私は、次のコードスニペットを変換しようとしました

そして、XCode IBに次の属性を与えて、Kerを調整しますenter image description here

しかし、実際には、アプリケーションが実行されているときにUIに影響を及ぼしていないようだし、インターフェースビルダーでもテキストが消えてしまいます。

誰かが私を助け、私が間違ったことを指摘してください。

ありがとうございました!

答えて

1

カーニングが更新されるたびにattributedTextを更新したいとします。

IB_DESIGNABLE 
@interface KerningLabel : UILabel 

@property (nonatomic) IBInspectable CGFloat kerning; 

@end 

とあなたの.m::だから、あなたの.hは次のようになります

@implementation KerningLabel 

- (void)setKerning:(CGFloat)kerning 
{ 
    _kerning = kerning; 

    if(self.attributedText) 
    { 
     NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText]; 
     [attribString addAttribute:NSKernAttributeName value:@(kerning) range:NSMakeRange(0, self.attributedText.length)]; 
     self.attributedText = attribString; 
    } 
} 

@end 
+0

パーフェクト!上記のコードで問題になった間違いを解決しました。これで、IBでカーニングを編集できるようになりました。 –