美文网首页
iOS自定义 UILabel可以使文字居上 居中 居下

iOS自定义 UILabel可以使文字居上 居中 居下

作者: 冯龙胜 | 来源:发表于2017-09-25 15:24 被阅读0次

    前言:做过iOS 的都知道,UILabel有让文字居左,居右,居中的属性,可是有时候我们在做项目的时候,可能会需要将label上的文字居上, 居中或者 居下这样的操作。那么今天我们就来说一说这种效果的实现方式。

    #import <UIKit/UIKit.h>

    typedefenum

    {

    VerticalAlignmentTop =0,// default

    VerticalAlignmentMiddle,

    VerticalAlignmentBottom,

    } VerticalAlignment;

    @interfaceBaseUILabel :UILabel

    {

    @private

    VerticalAlignment_verticalAlignment;

    }

    @property(nonatomic)VerticalAlignmentverticalAlignment;

    @end

    #import"BaseUILabel.h"

    @implementationBaseUILabel

    @synthesizeverticalAlignment =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 {

    CGRecttextRect = [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;

    }

    returntextRect;

    }

    -(void)drawTextInRect:(CGRect)requestedRect {

    CGRectactualRect = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];

    [superdrawTextInRect:actualRect];

    }

    @end

    这样我们在使用的时候,只要继承这个label类,然后选择想要实现效果的属性即可

    相关文章

      网友评论

          本文标题:iOS自定义 UILabel可以使文字居上 居中 居下

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