iOS UILabel控件默認文字位置是居中的,如圖所示:java
可是咱們常常碰到這樣的需求,但願文字向上置頂,或者向下置底,可是很遺憾,iOS API中並無提供相應的屬性和方法,須要咱們手動設置。ui
利用 分類(category)爲UILabel添加屬性 isTop 和 isBottom來控制文字是否置頂和置底。atom
實現:利用往文字後面活前面下面添加」\n」來實現文字填充滿整個UILable控件實現置頂/置頂效果spa
.h文件3d
#import <UIKit/UIKit.h> @interface UILabel (TextAlign) @property (nonatomic, assign) BOOL isTop; @property (nonatomic, assign) BOOL isBottom; @end
.m文件code
#import "UILabel+TextAlign.h" @implementation UILabel (TextAlign) -(void)setIsTop:(BOOL)isTop { if (isTop) { CGSize fontSize = [self.text sizeWithFont:self.font]; //控件的高度除以一行文字的高度 int num = self.frame.size.height/fontSize.height; //計算須要添加換行符個數 int newLinesToPad = num - self.numberOfLines; self.numberOfLines = 0; for(int i=0; i<newLinesToPad; i++) //在文字後面添加換行符"/n" self.text = [self.text stringByAppendingString:@"\n"]; } } -(void)setIsBottom:(BOOL)isBottom { if (isBottom) { CGSize fontSize = [self.text sizeWithFont:self.font]; //控件的高度除以一行文字的高度 int num = self.frame.size.height/fontSize.height; //計算須要添加換行符個數 int newLinesToPad = num - self.numberOfLines; self.numberOfLines = 0; for(int i=0; i<newLinesToPad; i++) //在文字前面添加換行符"/n" self.text = [NSString stringWithFormat:@" \n%@",self.text]; } } @end
使用方法:
導入頭文件orm
#import "UILabel+TextAlign.h"
而後設置屬性blog
//置頂 self.lb.isTop = YES; //置底 self.lb.isBottom = YES;
源碼免費下載地址:http://www.jinhusns.com/Products/Download/