1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Swift环境下实现UILabel居上 居中 居下对齐

Swift环境下实现UILabel居上 居中 居下对齐

时间:2023-12-15 06:08:47

相关推荐

Swift环境下实现UILabel居上 居中 居下对齐

首先在Xcode中新建.h文件,将以下代码复制进去

//// myUILabel.h// //// Created by yexiaozi_007 on 3/4/13.// Copyright (c) yexiaozi_007. All rights reserved.//#import <UIKit/UIKit.h>typedef enum{VerticalAlignmentTop = 0, // defaultVerticalAlignmentMiddle,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) 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,默认为居上

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。