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

來源:互聯網
上載者:User

標籤:copy   ica   fill   turn   div   atomic   r檔案   syn   ott   

首先在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{@privateVerticalAlignment _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居上 置中 居下對齊

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.