我有一个带有两行文本空间的 UILabel
。有时,当文本太短时,该文本会显示在标签的垂直中心。
如何垂直对齐文本以始终位于 UILabel
的顶部?
https://i.stack.imgur.com/TxzmG.jpg
无法在 UILabel
上设置垂直对齐,但您可以通过更改标签的框架来获得相同的效果。我已将标签设为橙色,以便您清楚地看到正在发生的事情。
这是执行此操作的快速简便的方法:
[myLabel sizeToFit];
https://i.stack.imgur.com/O7JEo.png
如果您有一个包含超过一行的较长文本的标签,请将 numberOfLines
设置为 0
(此处的零表示行数不受限制)。
myLabel.numberOfLines = 0;
[myLabel sizeToFit];
https://i.stack.imgur.com/08dRM.png
更长的版本
我将在代码中制作我的标签,以便您可以看到发生了什么。您也可以在 Interface Builder 中设置大部分内容。我的设置是一个基于视图的应用程序,带有我在 Photoshop 中制作的背景图像以显示边距(20 点)。标签是迷人的橙色,因此您可以看到尺寸的变化。
- (void)viewDidLoad
{
[super viewDidLoad];
// 20 point top and left margin. Sized to leave 20 pt at right.
CGRect labelFrame = CGRectMake(20, 20, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setBackgroundColor:[UIColor orangeColor]];
NSString *labelText = @"I am the very model of a modern Major-General, I've information vegetable, animal, and mineral";
[myLabel setText:labelText];
// Tell the label to use an unlimited number of lines
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
[self.view addSubview:myLabel];
}
使用 sizeToFit
的一些限制对居中或右对齐的文本起作用。这是发生的事情:
// myLabel.textAlignment = NSTextAlignmentRight;
myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
https://i.stack.imgur.com/DH18q.png
标签的大小仍为固定的左上角。您可以将原始标签的宽度保存在变量中并在 sizeToFit
之后设置它,或者给它一个固定宽度来解决这些问题:
myLabel.textAlignment = NSTextAlignmentCenter;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
CGRect myFrame = myLabel.frame;
// Resize the frame's width to 280 (320 - margins)
// width could also be myOriginalLabelFrame.size.width
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 280, myFrame.size.height);
myLabel.frame = myFrame;
https://i.stack.imgur.com/gedYP.png
请注意,sizeToFit
将遵循您的初始标签的最小宽度。如果您从一个 100 宽的标签开始并在其上调用 sizeToFit
,它将返回一个(可能非常高)宽度为 100(或更小)的标签。您可能希望在调整大小之前将标签设置为所需的最小宽度。
https://i.stack.imgur.com/RGI6v.png
其他一些需要注意的事项:
是否尊重 lineBreakMode
取决于它的设置方式。 NSLineBreakByTruncatingTail
(默认值)在 sizeToFit
之后被忽略,其他两种截断模式(头部和中间)也是如此。 NSLineBreakByClipping
也被忽略。 NSLineBreakByCharWrapping
照常工作。框架宽度仍然变窄以适合最右边的字母。
Mark Amery 在评论中对使用自动布局的 NIB 和 Storyboard 进行了修复:
如果您的标签包含在笔尖或情节提要中作为使用自动布局的 ViewController 的视图的子视图,那么将 sizeToFit 调用放入 viewDidLoad 将不起作用,因为在调用 viewDidLoad 后自动布局大小和位置子视图并将立即撤消您的 sizeToFit 调用的效果。但是,从 viewDidLayoutSubviews 中调用 sizeToFit 将起作用。
我的原始答案(供后代/参考):
这使用 NSString
方法 sizeWithFont:constrainedToSize:lineBreakMode:
计算适合字符串所需的帧高度,然后设置原点和宽度。
使用要插入的文本调整标签框架的大小。这样您就可以容纳任意数量的行。
CGSize maximumSize = CGSizeMake(300, 9999);
NSString *dateString = @"The date today is January 1st, 1999";
UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize dateStringSize = [dateString sizeWithFont:dateFont
constrainedToSize:maximumSize
lineBreakMode:self.dateLabel.lineBreakMode];
CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height);
self.dateLabel.frame = dateFrame;
设置新文本:myLabel.text = @"Some Text" 将最大行数设置为 0(自动):myLabel.numberOfLines = 0 将标签的框架设置为最大尺寸:myLabel.frame = CGRectMake(20, 20,200,800) 调用 sizeToFit 以减小帧大小,使内容刚好适合:[myLabel sizeToFit]
标签框现在的高度和宽度足以容纳您的文本。左上角应该保持不变。我只用左上对齐的文本对此进行了测试。对于其他对齐方式,您可能必须在之后修改框架。
另外,我的标签启用了自动换行。
参考扩展解决方案:
for(int i=1; i< newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n"];
应该替换为
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n "];
每个添加的换行符都需要额外的空间,因为 iPhone UILabels
的尾随回车似乎被忽略了:(
同样,alignBottom 也应该用 @" \n@%"
代替 "\n@%"
进行更新(循环初始化也必须由“for(int i=0...”) 替换。
以下扩展对我有用:
// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end
// -- file: UILabel+VerticalAlign.m
@implementation UILabel (VerticalAlign)
- (void)alignTop {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n "];
}
- (void)alignBottom {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
@end
然后在每次 yourLabel 文本分配后调用 [yourLabel alignTop];
或 [yourLabel alignBottom];
。
@implementation UILabel
之后的括号之间添加了 VerticalAlign
。作为 Objective-C 的新手,我以前没有遇到过这种语法。这个叫什么?
sizeWithFont:constrainedToSize:lineBreakMode:
和 sizeWithFont: 在 iOS7 中均已弃用。此外,此类别仅在 numberOfLines 大于 0 时适用于标签。
以防万一它对任何人有任何帮助,我遇到了同样的问题,但只需从使用 UILabel
切换到使用 UITextView
即可解决问题。我很欣赏这并不适合所有人,因为功能有点不同。
如果您确实切换到使用 UITextView
,您可以关闭所有滚动视图属性以及启用用户交互...这将迫使它更像一个标签。
https://i.stack.imgur.com/HB87m.png
UITextView
即可立即获得所需的结果。
没有混乱,没有大惊小怪
@interface MFTopAlignedLabel : UILabel
@end
@implementation MFTopAlignedLabel
- (void)drawTextInRect:(CGRect) rect
{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:@{NSFontAttributeName:self.font}];
rect.size.height = [attributedText boundingRectWithSize:rect.size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size.height;
if (self.numberOfLines != 0) {
rect.size.height = MIN(rect.size.height, self.numberOfLines * self.font.lineHeight);
}
[super drawTextInRect:rect];
}
@end
没有混乱,没有 Objective-c,没有大惊小怪,只有 Swift 3:
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSFontAttributeName: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
斯威夫特 4.2
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSAttributedString.Key.font: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
使用 Storyboard 的最简单方法:
将 Label 嵌入到 StackView 中,并在 Attribute Inspector 中设置 StackView 的以下两个属性:
1- Axis
到 Horizontal
,
2- Alignment
到 Top
https://i.stack.imgur.com/SVs0w.png
UILabel
放入某个 UIView
子类(普通的 UIView
通常就足够了)并让该标签向下增长的好主意。谢谢!
UIStackView
,只需将 UILabel
嵌入到 UIView
中。设置 UIView
约束以占用 UILabel
应增长到的最大空间。然后将 UILabel
设置为 UIView
的顶部、右侧和左侧,并将距离 >= 0
的约束也设置为底部。
就像上面的答案一样,但它不太正确,或者很容易打入代码,所以我对其进行了一些清理。将此扩展名添加到它自己的 .h 和 .m 文件中,或者直接粘贴到您打算使用它的实现上方:
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end
@implementation UILabel (VerticalAlign)
- (void)alignTop
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<= newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:@" \n"];
}
}
- (void)alignBottom
{
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i< newLinesToPad; i++)
{
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
}
@end
然后使用,将你的文本放入标签中,然后调用适当的方法来对齐它:
[myLabel alignTop];
或者
[myLabel alignBottom];
一种更快(也更脏)的方法是将 UILabel 的换行模式设置为“Clip”并添加固定数量的换行符。
myLabel.lineBreakMode = UILineBreakModeClip;
myLabel.text = [displayString stringByAppendingString:"\n\n\n\n"];
此解决方案不适用于所有人 - 特别是,如果您仍想在字符串末尾显示“...”,如果它超过了您显示的行数,则需要使用其中之一更长的代码位——但在很多情况下,这会让你得到你需要的东西。
UILineBreakModeWordWrap
。
您可以使用具有垂直对齐选项的 UITextField
而不是 UILabel
:
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.userInteractionEnabled = NO; // Don't allow interaction
我已经为此苦苦挣扎了很长时间,我想分享我的解决方案。
这将为您提供一个 UILabel
,它会将文本自动缩小到 0.5 比例并将文本垂直居中。这些选项在 Storyboard/IB 中也可用。
[labelObject setMinimumScaleFactor:0.5];
[labelObject setBaselineAdjustment:UIBaselineAdjustmentAlignCenters];
创建一个新类
标签顶部对齐
.h 文件
#import <UIKit/UIKit.h>
@interface KwLabelTopAlign : UILabel {
}
@end
.m 文件
#import "KwLabelTopAlign.h"
@implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect {
int lineHeight = [@"IglL" sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, 9999.0f)].height;
if(rect.size.height >= lineHeight) {
int textHeight = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(rect.size.width, rect.size.height)].height;
int yMax = textHeight;
if (self.numberOfLines > 0) {
yMax = MIN(lineHeight*self.numberOfLines, yMax);
}
[super drawTextInRect:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, yMax)];
}
}
@end
编辑
这是一个更简单的实现,它做同样的事情:
#import "KwLabelTopAlign.h"
@implementation KwLabelTopAlign
- (void)drawTextInRect:(CGRect)rect
{
CGFloat height = [self.text sizeWithFont:self.font
constrainedToSize:rect.size
lineBreakMode:self.lineBreakMode].height;
if (self.numberOfLines != 0) {
height = MIN(height, self.font.lineHeight * self.numberOfLines);
}
rect.size.height = MIN(rect.size.height, height);
[super drawTextInRect:rect];
}
@end
sizeToFit
解决方案不同,这实际上使 UILabel
将 any 文本放在顶部,即使您将较短的文本动态替换为较长的文本,反之亦然。
https://i.stack.imgur.com/yJFKP.png
在界面生成器中
将 UILabel 设置为最大可能文本的大小
在属性检查器中将行设置为“0”
在您的代码中
设置标签的文本
在标签上调用 sizeToFit
代码片段:
self.myLabel.text = @"Short Title";
[self.myLabel sizeToFit];
对于 Adaptive UI(iOS8 或更高版本),UILabel 的垂直对齐将通过更改属性 noOfLines
=0` 和 StoryBoard 来设置
调整 UILabel LefMargin、RightMargin 和 Top Margin 约束的约束。更改 Vertical=1000` 的内容压缩阻力优先级,以便 Vertical>Horizontal 。
https://i.stack.imgur.com/4LKFV.png
编辑:
noOfLines=0
并且以下约束足以达到预期的结果。
https://i.stack.imgur.com/TS4pR.png
创建 UILabel 的子类。奇迹般有效:
// TopLeftLabel.h
#import <Foundation/Foundation.h>
@interface TopLeftLabel : UILabel
{
}
@end
// TopLeftLabel.m
#import "TopLeftLabel.h"
@implementation TopLeftLabel
- (id)initWithFrame:(CGRect)frame
{
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect
{
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
@end
如here所述。
https://i.stack.imgur.com/gAZlM.png
我写了一个 util 函数来实现这个目的。你可以看看:
// adjust the height of a multi-line label to make it align vertical with top + (void) alignLabelWithTop:(UILabel *)label { CGSize maxSize = CGSizeMake(label.frame.size.width, 999); label.adjustsFontSizeToFitWidth = NO; // get actual height CGSize actualSize = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode]; CGRect rect = label.frame; rect.size.height = actualSize.height; label.frame = rect; }
。如何使用? (如果 lblHello 是由 Interface builder 创建的,所以我跳过了一些 UILabel 属性细节)
lblHello.text = @"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"; lblHello.numberOfLines = 5; [Utils alignLabelWithTop:lblHello];
我也在我的博客上写了一篇文章:http://fstoke.me/blog/?p=2819
使用 textRect(forBounds:limitedToNumberOfLines:)
。
class TopAlignedLabel: UILabel {
override func drawText(in rect: CGRect) {
let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
super.drawText(in: textRect)
}
}
看了一会代码,以及介绍页面中的代码,发现都尝试修改label的frame size,这样就不会出现默认居中垂直对齐了。
然而,在某些情况下,我们确实希望标签占据所有这些空间,即使标签确实有这么多文本(例如,具有相同高度的多行)。
在这里,我使用了另一种方法来解决它,只需将换行符填充到标签的末尾(请注意,我实际上继承了 UILabel
,但这不是必需的):
CGSize fontSize = [self.text sizeWithFont:self.font];
finalHeight = fontSize.height * self.numberOfLines;
finalWidth = size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i = 0; i < newLinesToPad; i++)
{
self.text = [self.text stringByAppendingString:@"\n "];
}
我在这里接受了建议并创建了一个视图,它可以包装 UILabel 并将其调整大小并设置行数以使其顶部对齐。简单地把一个 UILabel 作为一个子视图:
@interface TopAlignedLabelContainer : UIView
{
}
@end
@implementation TopAlignedLabelContainer
- (void)layoutSubviews
{
CGRect bounds = self.bounds;
for (UILabel *label in [self subviews])
{
if ([label isKindOfClass:[UILabel class]])
{
CGSize fontSize = [label.text sizeWithFont:label.font];
CGSize textSize = [label.text sizeWithFont:label.font
constrainedToSize:bounds.size
lineBreakMode:label.lineBreakMode];
label.numberOfLines = textSize.height / fontSize.height;
label.frame = CGRectMake(0, 0, textSize.width,
fontSize.height * label.numberOfLines);
}
}
}
@end
您可以使用TTTAttributedLabel,它支持垂直对齐。
@property (nonatomic) TTTAttributedLabel* label;
<...>
//view's or viewController's init method
_label.verticalAlignment = TTTAttributedLabelVerticalAlignmentTop;
我发现这个问题的答案现在有点过时了,所以为那里的自动布局粉丝添加这个。
自动布局使这个问题变得非常简单。假设我们将标签添加到 UIView *view
,以下代码将完成此操作:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setText:@"Some text here"];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
[view addSubview:label];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:@{@"label": label}]];
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]" options:0 metrics:nil views:@{@"label": label}]];
标签的高度将自动计算(使用它的 intrinsicContentSize
)并且标签将在 view
的顶部水平边对边定位。
我已经使用了很多上面的方法,只是想添加一个我用过的快速和肮脏的方法:
myLabel.text = [NSString stringWithFormat:@"%@\n\n\n\n\n\n\n\n\n",@"My label text string"];
确保字符串中的换行符数量会导致任何文本填充可用的垂直空间,并设置 UILabel 以截断任何溢出的文本。
因为有时候足够好就是足够好。
UITextView
动态加载视图时了解到,它可以调用 dlopen
以支持文本输入。这可能会导致 UI 线程严重滞后,因此这种方法的性能要高得多!
我想要一个标签,它能够有多行、最小字体大小,并且在它的父视图中水平和垂直居中。我以编程方式将标签添加到视图中:
- (void) customInit {
// Setup label
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.label.numberOfLines = 0;
self.label.lineBreakMode = UILineBreakModeWordWrap;
self.label.textAlignment = UITextAlignmentCenter;
// Add the label as a subview
self.autoresizesSubviews = YES;
[self addSubview:self.label];
}
然后当我想更改标签的文本时......
- (void) updateDisplay:(NSString *)text {
if (![text isEqualToString:self.label.text]) {
// Calculate the font size to use (save to label's font)
CGSize textConstrainedSize = CGSizeMake(self.frame.size.width, INT_MAX);
self.label.font = [UIFont systemFontOfSize:TICKER_FONT_SIZE];
CGSize textSize = [text sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
while (textSize.height > self.frame.size.height && self.label.font.pointSize > TICKER_MINIMUM_FONT_SIZE) {
self.label.font = [UIFont systemFontOfSize:self.label.font.pointSize-1];
textSize = [ticker.blurb sizeWithFont:self.label.font constrainedToSize:textConstrainedSize];
}
// In cases where the frame is still too large (when we're exceeding minimum font size),
// use the views size
if (textSize.height > self.frame.size.height) {
textSize = [text sizeWithFont:self.label.font constrainedToSize:self.frame.size];
}
// Draw
self.label.frame = CGRectMake(0, self.frame.size.height/2 - textSize.height/2, self.frame.size.width, textSize.height);
self.label.text = text;
}
[self setNeedsDisplay];
}
希望对某人有所帮助!
FXLabel (on github) 通过将 label.contentMode
设置为 UIViewContentModeTop
开箱即用地执行此操作。这个组件不是我做的,但它是我经常使用的一个组件,有很多功能,而且看起来效果很好。
对于阅读此内容的任何人,因为标签内的文本不是垂直居中的,请记住,某些字体类型的设计并不相同。例如,如果您创建一个 zapfino 大小为 16 的标签,您将看到文本没有完全垂直居中。
但是,使用 helvetica 会使您的文本垂直居中。
子类 UILabel 并约束绘图矩形,如下所示:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
[super drawTextInRect:rect];
}
我尝试了涉及换行填充的解决方案,但在某些情况下遇到了不正确的行为。根据我的经验,像上面那样约束绘图矩形比使用 numberOfLines
更容易。
PS 你可以想象用这种方式轻松支持 UIViewContentMode:
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
if (self.contentMode == UIViewContentModeTop) {
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
else if (self.contentMode == UIViewContentModeBottom) {
rect.origin.y = MAX(0, rect.size.height - sizeThatFits.height);
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
}
[super drawTextInRect:rect];
}
如果您使用自动布局,请将垂直 contentHuggingPriority 设置为 1000,无论是在代码中还是在 IB 中。在 IB 中,您可能必须通过将其优先级设置为 1 然后删除它来删除高度约束。
只要您不执行任何复杂的任务,您就可以使用 UITextView
而不是 UILabels
。
禁用滚动。
如果您希望文本完全显示,只需用户 sizeToFit
和 sizeThatFits:
方法
迅速地,
let myLabel : UILabel!
使您的标签文本适合屏幕并且位于顶部
myLabel.sizeToFit()
使您的标签字体适合屏幕宽度或特定宽度大小。
myLabel.adjustsFontSizeToFitWidth = YES
和一些 textAlignment 标签:
myLabel.textAlignment = .center
myLabel.textAlignment = .left
myLabel.textAlignment = .right
myLabel.textAlignment = .Natural
myLabel.textAlignment = .Justified
[myLabel sizeToFit]
的旧语法改变了语法。谢谢!
这是一个旧的解决方案,在 iOS >= 6 上使用自动布局
我的解决方案:
自己分割线(忽略标签环绕设置)自己画线(忽略标签对齐)
@interface UITopAlignedLabel : UILabel
@end
@implementation UITopAlignedLabel
#pragma mark Instance methods
- (NSArray*)splitTextToLines:(NSUInteger)maxLines {
float width = self.frame.size.width;
NSArray* words = [self.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray* lines = [NSMutableArray array];
NSMutableString* buffer = [NSMutableString string];
NSMutableString* currentLine = [NSMutableString string];
for (NSString* word in words) {
if ([buffer length] > 0) {
[buffer appendString:@" "];
}
[buffer appendString:word];
if (maxLines > 0 && [lines count] == maxLines - 1) {
[currentLine setString:buffer];
continue;
}
float bufferWidth = [buffer sizeWithFont:self.font].width;
if (bufferWidth < width) {
[currentLine setString:buffer];
}
else {
[lines addObject:[NSString stringWithString:currentLine]];
[buffer setString:word];
[currentLine setString:buffer];
}
}
if ([currentLine length] > 0) {
[lines addObject:[NSString stringWithString:currentLine]];
}
return lines;
}
- (void)drawRect:(CGRect)rect {
if ([self.text length] == 0) {
return;
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, self.textColor.CGColor);
CGContextSetShadowWithColor(context, self.shadowOffset, 0.0f, self.shadowColor.CGColor);
NSArray* lines = [self splitTextToLines:self.numberOfLines];
NSUInteger numLines = [lines count];
CGSize size = self.frame.size;
CGPoint origin = CGPointMake(0.0f, 0.0f);
for (NSUInteger i = 0; i < numLines; i++) {
NSString* line = [lines objectAtIndex:i];
if (i == numLines - 1) {
[line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeTailTruncation];
}
else {
[line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeClip];
}
origin.y += self.font.lineHeight;
if (origin.y >= size.height) {
return;
}
}
}
@end
不定期副业成功案例分享