全國(guó)服務熱線:0551-64931480

09
20-01

iOS UILabel垂直居中

雲庫科技 767196 0

平常開(kāi)發(fā)設計的那時候將(jiāng)會(huì)會(huì)碰到這(zhè)類難題:當一個UILabel的frame的高度設置的過(guò)大時,發(fā)覺UILabel是垂直居中的,有的要求是必須將(jiāng)這(zhè)一Label豎直往上顯示信息,以前的方法是測算出label.text的字體樣(yàng)式所占有的frame尺寸,依據這(zhè)一尺寸再再次設置label的frame值,不免會(huì)一些麻煩,前陣子封裝了個自定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)
暫無評論

發(fā)表評論 取消回複