您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

分享一個可垂直對齊的 UILabel:頂端、居中、底部隨你挑

編輯:iOS 開發綜合

UILabel 的文字預設是垂直居中的,但實務上常會需要「文字靠頂對齊」或「靠底對齊」,而系統並沒有提供現成開關。解法是繼承 UILabel,覆寫兩個方法,把文字矩形(text rect)的位置自己算回來。

一、頭文件:用列舉描述對齊方式

#import <Foundation/Foundation.h>

typedef enum VerticalAlignment {
    VerticalAlignmentTop,
    VerticalAlignmentMiddle,
    VerticalAlignmentBottom,
} VerticalAlignment;

@interface VerticallyAlignedLabel : UILabel
{
@private
    VerticalAlignment verticalAlignment_;
}

@property (nonatomic, assign) VerticalAlignment verticalAlignment;

@end

二、實現文件

#import "VerticallyAlignedLabel.h"

@implementation VerticallyAlignedLabel

@synthesize verticalAlignment = verticalAlignment_;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        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

這兩個方法為什麼要一起覆寫

textRectForBounds:limitedToNumberOfLines: 負責回報文字實際要佔的矩形,UILabel 在計算自身尺寸(例如 sizeToFit)時會呼叫它;drawTextInRect: 則負責真正把字畫上去。如果只改前者,繪製時仍會落在系統算好的位置;如果只改後者,label 的固有尺寸計算又會失準。兩邊都改,對齊才會在顯示與版面計算上一致。

另外別忘了 setter 裡的 setNeedsDisplay——對齊方式改了就要重畫,少了這行會出現「設定了但畫面沒變」的狀況。三個分支的算法都很直觀:頂對齊直接把 y 對齊 bounds 原點,底對齊用容器高度減掉文字高度,居中則取差值的一半。

摘自 dread

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved