1. 程式人生 > >Swift環境下實現UILabel居上 居中 居下對齊

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

label 復制 圖例 limit ret requested art urn int

首先在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。默覺得居上


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