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

时间:2023-03-08 17:10:20

在iOS中默认的UILabel中的文字在竖直方向上只能居中对齐,博主参考国外网站,从UILabel继承了一个新类,实现了居上对齐,居中对齐,居下对齐。具体如下:

  1. //
  2. //  myUILabel.h
  3. //
  4. //
  5. //  Created by yexiaozi_007 on 3/4/13.
  6. //  Copyright (c) 2013 yexiaozi_007. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. typedef enum
  10. {
  11. VerticalAlignmentTop = 0, // default
  12. VerticalAlignmentMiddle,
  13. VerticalAlignmentBottom,
  14. } VerticalAlignment;
  15. @interface myUILabel : UILabel
  16. {
  17. @private
  18. VerticalAlignment _verticalAlignment;
  19. }
  20. @property (nonatomic) VerticalAlignment verticalAlignment;
  21. @end
  1. //
  2. //  myUILabel.m
  3. //
  4. //
  5. //  Created by yexiaozi_007 on 3/4/13.
  6. //  Copyright (c) 2013 yexiaozi_007. All rights reserved.
  7. //
  8. #import "myUILabel.h"
  9. @implementation myUILabel
  10. @synthesize verticalAlignment = verticalAlignment_;
  11. - (id)initWithFrame:(CGRect)frame {
  12. if (self = [super initWithFrame:frame]) {
  13. self.verticalAlignment = VerticalAlignmentMiddle;
  14. }
  15. return self;
  16. }
  17. - (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {
  18. verticalAlignment_ = verticalAlignment;
  19. [self setNeedsDisplay];
  20. }
  21. - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
  22. CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
  23. switch (self.verticalAlignment) {
  24. case VerticalAlignmentTop:
  25. textRect.origin.y = bounds.origin.y;
  26. break;
  27. case VerticalAlignmentBottom:
  28. textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
  29. break;
  30. case VerticalAlignmentMiddle:
  31. // Fall through.
  32. default:
  33. textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
  34. }
  35. return textRect;
  36. }
  37. -(void)drawTextInRect:(CGRect)requestedRect {
  38. CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
  39. [super drawTextInRect:actualRect];
  40. }
  41. @end

在使用时:

    1. lbl_mylabel = [[myUILabel alloc] initWithFrame:CGRectMake(20, 50, 150, 600)];
    2. UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"halfTransparent.png"]];//使用半透明图片作为label的背景色
    3. lbl_mylabel.backgroundColor = color;
    4. lbl_mylabel.textAlignment = UITextAlignmentLeft;
    5. lbl_mylabel.textColor = UIColor.whiteColor;
    6. lbl_mylabel.lineBreakMode = UILineBreakModeWordWrap;
    7. lbl_mylabel.numberOfLines = 0;
    8. [lbl_mylabel setVerticalAlignment:VerticalAlignmentTop];
    9. [self addSubview:lbl_mylabel];