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

被折叠的 条评论
为什么被折叠?



