自定義UILabel,具有居上/居下/居中的功能


首先在.h中

//

//  MyLabel.h

//  WuXianMoney

//

//  Created by GF on 16/4/13.

//  Copyright © 2016 WXDL. All rights reserved.

//


#import <UIKit/UIKit.h>

typedef enum

{

    VerticalAlignmentTop = 0,// default

    VerticalAlignmentMiddle,

    VerticalAlignmentBottom,

} VerticalAlignment;

@interface MyLabel : UILabel


{

@private

    VerticalAlignment _verticalAlignment;

}


@property (nonatomic)VerticalAlignment verticalAlignment;

@end


然後在.m中

//

//  MyLabel.m

//  WuXianMoney

//

//  Created by GF on 16/4/13.

//  Copyright © 2016 WXDL. All rights reserved.

//


#import "MyLabel.h"


@implementation MyLabel

@synthesize verticalAlignment =verticalAlignment_;


- (id)initWithFrame:(CGRect)frame {

    if (self = [superinitWithFrame:frame]) {

        self.verticalAlignment =VerticalAlignmentMiddle;

    }

    returnself;

}


- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {

    verticalAlignment_ = verticalAlignment;

    [selfsetNeedsDisplay];

}


- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {

    CGRect textRect = [supertextRectForBounds:boundslimitedToNumberOfLines:numberOfLines];

    switch (self.verticalAlignment) {

        caseVerticalAlignmentTop:

            textRect.origin.y = bounds.origin.y;

            break;

        caseVerticalAlignmentBottom:

            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;

            break;

        caseVerticalAlignmentMiddle:

            // 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 = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];

    [superdrawTextInRect:actualRect];

}

@end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章