Change character spacing on UILabel within Interface Builder

前端 未结 13 2644
说谎
说谎 2020-12-23 09:21

Is there anyway to change the character spacing (track) on UILabel text using Interface Builder? If not, is there a way to do it programmatically on an existing UILabel that

13条回答
  •  臣服心动
    2020-12-23 09:40

    try this!!

    create CustomLabel class

    @interface CustomLabel : UILabel
    @property (assign, nonatomic) CGFloat myLineSpacing;
    @end
    
    
    @implementation CustomLabel
    
    - (void)setMyLineSpacing:(CGFloat)myLineSpacing {
        _myLineSpacing = myLineSpacing;
        self.text = self.text;
    }
    
    - (void)setText:(NSString *)text {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = _myLineSpacing;
        paragraphStyle.alignment = self.textAlignment;
        NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyle};
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text
                                                                             attributes:attributes];
        self.attributedText = attributedText;
    }
    

    and set runtime attribute

    enter image description here

    Note this is actually line spacing (also called leading .. in the very old days (pre-digital) you'd put lead (the metal) between lines to increase the gap between lines. For spacing between letters, that is called kerning .. here's how to do kerning https://stackoverflow.com/a/21141156/294884

提交回复
热议问题