iOS UILabel Text Top/Bottom Implementation

The default text position for the iOS UILabel control is centered, as shown in the figure:

 

But we often encounter the need to put text up to the top or down to the bottom, but unfortunately, there are no corresponding properties and methods in the iOS API that need to be set manually.

Use categories to add attributes isTop and isBottom to the UILabel to control whether text is placed at the top and bottom.

Implement: Use add "\n" to live front and bottom after text to fill the entire UILable control with text to achieve top/top effect

.h file

#import <UIKit/UIKit.h>

@interface UILabel (TextAlign)

@property (nonatomic, assign) BOOL isTop;
@property (nonatomic, assign) BOOL isBottom;

@end

 

.m file

#import "UILabel+TextAlign.h"

@implementation UILabel (TextAlign)

-(void)setIsTop:(BOOL)isTop {

    if (isTop) {

        CGSize fontSize = [self.text sizeWithFont:self.font];
        //The height of the control divided by the height of a line of text
        int num = self.frame.size.height/fontSize.height;
        //Calculate the number of line breaks that need to be added
        int newLinesToPad = num  - self.numberOfLines;
        self.numberOfLines = 0;
        for(int i=0; i<newLinesToPad; i++)
            //Add line break'/n'after text
            self.text = [self.text stringByAppendingString:@"\n"];
    }
}

-(void)setIsBottom:(BOOL)isBottom {

    if (isBottom) {
        CGSize fontSize = [self.text sizeWithFont:self.font];
        //The height of the control divided by the height of a line of text
        int num = self.frame.size.height/fontSize.height;
        //Calculate the number of line breaks that need to be added
        int newLinesToPad = num  - self.numberOfLines;
        self.numberOfLines = 0;
        for(int i=0; i<newLinesToPad; i++)
            //Add line break'/n'before text
            self.text = [NSString stringWithFormat:@" \n%@",self.text];
    }
}

@end

 

Usage:
Import header file

#import "UILabel+TextAlign.h"

Then set properties

//Set Top
self.lb.isTop = YES;

//Bottom setting
self.lb.isBottom = YES;
Free source download address: http://www.jinhusns.com/Products/Download/

 

Tags: iOS

Posted on Wed, 15 Jul 2020 12:15:05 -0400 by wmhop