博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift环境下实现UILabel居上 居中 居下对齐
阅读量:7002 次
发布时间:2019-06-27

本文共 2243 字,大约阅读时间需要 7 分钟。

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

////  myUILabel.h//  ////  Created by yexiaozi_007 on 3/4/13.//  Copyright (c) 2013 yexiaozi_007. All rights reserved.//#import 
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。默觉得居上

你可能感兴趣的文章
WPF触控程序开发(四)——MultiTouchVista_-_second_release_-_refresh_2的救赎
查看>>
mysql @value := 用法
查看>>
ASP.NET CORE系列【二】使用Entity Framework Core进行增删改查
查看>>
C# 判断用户是否对路径拥有访问权限
查看>>
Dubbo 源码分析 - 服务导出
查看>>
sqlserver 存储过程中使用临时表到底会不会导致重编译
查看>>
webpack-cli解决办法
查看>>
防火墙
查看>>
Confluence 6 自定义默认空间内容
查看>>
[剑指offer] 连续子数组的最大和
查看>>
HDU 2147 kiki's game(规律,博弈)
查看>>
TP5视频上传,商城增加视频上传功能
查看>>
Markdown语法学习记录
查看>>
Maupassant主题优化、屠城hexo主题优化版
查看>>
python:深入pip的安装源
查看>>
《算经十书》
查看>>
ant build文件详解
查看>>
java之JMS
查看>>
jquery-weui微信支付报错问题解决
查看>>
《Groovy极简教程》第7章 Groovy与Gradle
查看>>