iOS UILabel文字置頂或者文字居下的方法
#import <UIKit/UIKit.h>
@interface UILabel (TextAlign)
@property (nonatomic, assign) BOOL isTop;
@property (nonatomic, assign) BOOL isBottom;@end
#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
呼叫方法
self.label.isTop = YES;