美文网首页iOS企业级开发实用技术iOS Developer
UILabel实现文字居上,居下,居中

UILabel实现文字居上,居下,居中

作者: 强强刘 | 来源:发表于2016-12-12 14:44 被阅读59次

    应用场景,使用轻量级UILabel实现文字居上显示,或者居下显示的特殊UI要求下,使用频率不高(使用UITextview和UITextFiled也可以做,但是个人感觉不太合适)

    代码如下:
    LQLable.h

    #import <UIKit/UIKit.h>
    
    typedef NS_ENUM(NSUInteger, LQTextAlignment) {
        LQTextAlignmentTop,
        LQTextAlignmentMiddle,
        LQTextAlignmentBottom,
    };
    
    @interface LQLabel : UILabel
    
    @property (nonatomic, assign) LQTextAlignment textAlignment;
    @end
    

    LQLable.m

    #import "LQLabel.h"
    
    @interface LQLabel ()
    
    @end
    
    @implementation LQLabel
    
    @synthesize textAlignment = textAlignment_;
    
    - (id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            self.textAlignment = LQTextAlignmentMiddle;
        }
        return self;
    }
    
    -(void)setTextAlignment:(LQTextAlignment)textAlignment {
        textAlignment_ = textAlignment;
        [self setNeedsDisplay];
    }
    
    
    - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
        CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
        switch (self.textAlignment) {
            case LQTextAlignmentTop:
                textRect.origin.y = bounds.origin.y;
                break;
            case LQTextAlignmentBottom:
                textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
                break;
            case LQTextAlignmentMiddle:
                
            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实现文字居上,居下,居中

        本文链接:https://www.haomeiwen.com/subject/ctmmmttx.html