iOS的UILabel设置居上对齐,居下对齐

西门桃桃 2020-07-13 PM 150℃ 0条

需求:

  1. 限制两行,超出部分显示省略号...
  2. 要求自动居上对齐

实现方案:

  1. 文本后面加多一些\n
  2. 修改高度
  3. 重新绘制UILabel

第一种方式会导致不再显示省略号,第二种方式需要每次使用时计算文字占用高度不方便。所以最后我使用第三种方式实现:
.h文件中声明一个枚举类型用来设置对齐方式:

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

@property (nonatomic, assign) VerticalAlignment verticalAlignment;

.m中实现设置对齐方法:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.verticalAlignment = VerticalAlignmentMiddle;
    }
    return self;
}

- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
    _verticalAlignment = verticalAlignment;
    [self setNeedsLayout];
}


- (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];
}
标签: iOS, Objective-C, UILabel

非特殊说明,本博所有文章均为博主原创。

评论啦~