UILabel设置两行高度,一行时不想在中间想要在上边显示看这里

2021-04-16  本文已影响0人  seul

UILabel设置的固定的2行高度,但是一行时候显示在中间,两行的在上面 如图:


image

看起来就很丑,产品肯定是不让的,优化时候看到了一个好的文章正好可以解决这个问题
地址
亲测有效 代码在下面

修改后

.m代码

#import "TwoLineCenterLabel.h"
@implementation TwoLineCenterLabel


- (id)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 = bounds.origin.y;
            break;
        case VerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case VerticalAlignmentMiddle:
            // 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 = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:actualRect];
}


@end

.h代码

#import <UIKit/UIKit.h>

typedef enum
{
    VerticalAlignmentTop = 0, // default
    VerticalAlignmentMiddle,
    VerticalAlignmentBottom,
} VerticalAlignment;

NS_ASSUME_NONNULL_BEGIN

@interface TwoLineCenterLabel : UILabel
{
@private
    VerticalAlignment _verticalAlignment;
}
@property (nonatomic) VerticalAlignment verticalAlignment;

@end

NS_ASSUME_NONNULL_END

使用时UILabel继承TwoLineCenterLabel就可以使用了

可以设置不同属性满足不同需求

  //放到顶部
     [label setVerticalAlignment:VerticalAlignmentTop];
    //放到中间
  //  [label setVerticalAlignment:VerticalAlignmentMiddle];
    //放到最下面
   // [label setVerticalAlignment:VerticalAlignmentBottom];
上一篇 下一篇

猜你喜欢

热点阅读