
首先在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"
然后右键拖动Label或者按住Control键左键拖动连线到Label所在的父VIEw的Class中生成Outlet,如果之前已经连线好,则改完Custom Class后,将连线生成代码中的UILabel改为myUILabel,示意图如下
然后就可以调用该label的类方法
label.verticalAlignment = VerticalAlignmentBottom按上方代码可以实现居下对其,居中 居上 分别将代码中的Bottom改为MIDdle和top,默认为居上 总结
以上是内存溢出为你收集整理的Swift环境下实现UILabel居上 居中 居下对齐全部内容,希望文章能够帮你解决Swift环境下实现UILabel居上 居中 居下对齐所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)