Swift環境下實現UILabel居上 居中 居下對齊

首先在Xcode中新建.h文件,將以下代碼複製進去

//
//  myUILabel.h
//  
//
//  Created by yexiaozi_007 on 3/4/13.
//  Copyright (c) 2013 yexiaozi_007. All rights reserved.
//

#import <UIKit/UIKit.h>
typedef enum
{
    VerticalAlignmentTop = 0, // default
    VerticalAlignmentMiddle,
    VerticalAlignmentBottom,
} VerticalAlignment;
@interface myUILabel : UILabel
{
@private
VerticalAlignment _verticalAlignment;
}

@property (nonatomic) VerticalAlignment verticalAlignment;

@end

再新建一個.m文件,拷入以下代碼

//
//  myUILabel.m
//  
//
//  Created by yexiaozi_007 on 3/4/13.
//  Copyright (c) 2013 yexiaozi_007. All rights reserved.
//

#import "myUILabel.h"

@implementation myUILabel
@synthesize verticalAlignment = verticalAlignment_;

- (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

如果這是你導入的第一個.m文件Xcode會提示你要不要創建Bridging-Header,選Ok

在新創建的Bridging-Header文件裏拷入下方代碼

#import "myUILabel.h"


然後打開你的StoryBoard,點選你想要更改對齊方式的Label,將其Class改爲myUILabel,示意圖如下



然後右鍵拖動Label或者按住Control鍵左鍵拖動連線到Label所在的父View的Class中生成Outlet,如果之前已經連線好,則改完Custom Class後,將連線生成代碼中的UILabel改爲myUILabel,示意圖如下


然後就可以調用該label的類方法

label.verticalAlignment = VerticalAlignmentBottom

按上方代碼可以實現居下對其,居中 居上 分別將代碼中的Bottom改爲Middle和Top,默認爲居上


發佈了45 篇原創文章 · 獲贊 2 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章