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

该博客介绍了一个自定义的UILabel类,名为MyLabel,支持文本的垂直居上、居中和居下对齐。通过枚举类型VerticalAlignment设置对齐方式,并在setVerticalAlignment方法中更新显示。在textRectForBounds方法中,根据不同的垂直对齐选项调整文本的显示位置,从而实现了自定义的垂直对齐功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


首先在.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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值