平常开发设计的那时候将会会碰到这类难题:当一个UILabel的frame的高度设置的过大时,发觉UILabel是垂直居中的,有的要求是必须将这一Label竖直往上显示信息,以前的方法是测算出label.text的字体样式所占有的frame尺寸,依据这一尺寸再再次设置label的frame值,不免会一些麻烦,前阵子封裝了个自定label保持的垂直居中的设置。废话很少说,上编码。

//  
//  JFLabel.h  
//  BobcareDoctorApp  
//  
//  
#import <UIKit/UIKit.h>  
typedef enum  
{  
    VerticalAlignmentTop = 0, // default  
    VerticalAlignmentMiddle,  
    VerticalAlignmentBottom,  
} VerticalAlignment;  
@interface JFLabel : UILabel  
{  
@private  
    VerticalAlignment _verticalAlignment;  
}  
@property (nonatomic) VerticalAlignment verticalAlignment;  
@end  
//  
//  JFLabel.m  
//  BobcareDoctorApp  
//  
//  
#import "JFLabel.h"  
@implementation JFLabel  
@synthesize verticalAlignment = verticalAlignment_;   
- (id)initWithFrame:(CGRect)frame {  
    if (self = [super initWithFrame:frame]) {  
        self.verticalAlignment = VerticalAlignmentMiddle;  
    }  
    return self;  
}  
- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {  
    verticalAlignment_ = verticalAlignment;  
    [self setNeedsDisplay];  
}  
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {  
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];  
    switch (self.verticalAlignment) {  
        case VerticalAlignmentTop:  
            textRect.origin.y = bounds.origin.y;  
            break;  
        case VerticalAlignmentBottom:  
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;  
            break;  
        case VerticalAlignmentMiddle:  
            // Fall through.  
        default:  
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;  
    }  
    return textRect;  
}  
-(void)drawTextInRect:(CGRect)requestedRect {  
    CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];  
    [super drawTextInRect:actualRect];  
}  
@end  

封裝的类承继自UILabel,必须设置垂直居中时立即设置特性就就行了。
启用实例编码:

- (JFLabel *)titleLabel  
{  
    if (!_titleLabel)  
    {  
        _titleLabel = [[JFLabel alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH - CASE_IMAGE_VIEW_WIDTH - 15 - 20 - 5, 40)];  
        _titleLabel.text = @"检测垂直居中文本";  
        _titleLabel.font = [UIFont systemFontOfSize:16];  
        _titleLabel.numberOfLines = 0;  
        _titleLabel.textColor = [UIColor blackColor];  
        _titleLabel.verticalAlignment = VerticalAlignmentTop;//垂直居中  
    }  
    return _titleLabel;  
}  

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部