• 自定义UILabel设置垂直方向的居上,居中,居下


    IOS系统框架中UILabel的属性textAlignment只调整水平方向的居中,居左,居右,而没有垂直方向的调整。所以要自定义一个继承自UILabel的类,在类的实现文件中进行文字的重绘,达到垂直方向的位置调整。

    新建一个类文件,继承自UILabel,头文件如下:

    #import <UIKit/UIKit.h>
    
    typedef NS_ENUM(NSInteger,VerticalAlignment){
        VerticalAlignmentTop,
        VerticalAlignmentMiddle,
        VerticalAlignmentBottom
    };
    
    @interface FSVerticallyAlignedLabel : UILabel
    
    @property (nonatomic,assign) VerticalAlignment verticalAlignment;
    
    @end
    

     在.m文件中,实现verticalAlignment的设置方法

    @implementation FSVerticallyAlignedLabel
    
    - (id)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            self.verticalAlignment = VerticalAlignmentMiddle;
        }
        
        return self;
    }
    
    /**
     *  设置属性方法
     *
     *  @param verticalAlignment 垂直调整位置
     */
    - (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment
    {
        _verticalAlignment = verticalAlignment;
        
        [self setNeedsDisplay];
    }
    
    /**
     *  计算文字的矩形区域
     *
     *  @param bounds        label矩形区域
     *  @param numberOfLines 行数
     *
     *  @return 返回文字所占的矩形区域
     */
    - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
    {
        CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
        
        //通过设定字体区域的y值来调整垂直位置
        switch (self.verticalAlignment) {
            case VerticalAlignmentTop:
                textRect.origin.y = bounds.origin.y;
                break;
            case VerticalAlignmentMiddle:
                textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
                break;
            case VerticalAlignmentBottom:
                textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
                break;
        }
        
        return textRect;
    }
    
    //重写父类方法
    - (void)drawTextInRect:(CGRect)rect
    {
        CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
        [super drawTextInRect:actualRect];
    }
    
    @end
    
  • 相关阅读:
    C语言基础---字符指针变量和字符数组的区别
    C语言基础---编写C语言代码过程中易忽略的点
    C语言简介---通过指针引用多维数组
    C语言基础---特殊的变量类型(结构体、枚举、共用体)
    C语言基础---指针简述
    C语言基础---C语言中的变量与内存空间的关系
    嵌入式开发中常用到的C语言库函数
    SVN使用---简介
    视频编解码相关基础知识(二)---H.264简介
    MybatisPlus MetaObjectHandler 配置
  • 原文地址:https://www.cnblogs.com/csdnmc/p/5407079.html
Copyright © 2020-2023  润新知