美文网首页
【OC】iOS的UILabel设置上部对齐,中间对齐,底部对齐

【OC】iOS的UILabel设置上部对齐,中间对齐,底部对齐

作者: 鄒賢 | 来源:发表于2016-11-18 12:01 被阅读0次

           系统中的UILabel对齐方式只有左、中、右对齐方式,有时候希望文本内容上部、中间和底部对齐,所以下面自定义一个继承UILabel的类来实现上部、中间和底部对齐。先来看一下.h文件:

    .h 文件

    typedef NS_ENUM (NSInteger ,VerticalAlignment){
    VerticalAlignmentTop = 0,  //上居中
    VerticalAlignmentMiddle, //中居中
    VerticalAlignmentBottom //低居中
    };
    
    @interface VerticalLabel : UILabel
    
    @property (nonatomic,assign)VerticalAlignment verticalAlignment;
    
    @end
    

    .m文件

    @implementation VerticalLabel
    
    -(instancetype)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 = self.bounds.origin.y;
            break;
    
            case VerticalAlignmentMiddle:
            break;
    
            case VerticalAlignmentBottom:
                textRect.origin.y = bounds.origin.y +       bounds.size.height - textRect.size.height;
            break;
    
            default:
                textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
            break;
    }
        return textRect;
    }
    -(void)drawTextInRect:(CGRect)rect{
        CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
        [super drawTextInRect:actualRect];
    }
    
    使用此类:请看下面的使用的例子
    VerticalLabel *textLabel = [[VerticalLabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    textLabel.numberOfLines = 1;
    textLabel.font = [UIFont systemFontOfSize:18];
    textLabel.text = @"哈哈哈哈哈";
    textLabel.textColor = [UIColor redColor];
    textLabel.backgroundColor = [UIColor greenColor ];
    textLabel.verticalAlignment = VerticalAlignmentTop;
    textLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:textLabel];
    

    搭配系统的属性textAlignment,可以组成左上角对齐,右上角对齐,左居中对齐,右居中对齐,左下角对齐,右下角对齐,居中。

    相关文章

      网友评论

          本文标题:【OC】iOS的UILabel设置上部对齐,中间对齐,底部对齐

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