gpt4 book ai didi

iphone - 如何为 iOS 应用程序的 UILabel 设置左上对齐?

转载 作者:IT王子 更新时间:2023-10-29 07:30:11 25 4
gpt4 key购买 nike

我在我的 nib 文件中添加了一个标签,然后要求该标签左上对齐。由于我在运行时提供文本,因此不确定有多少行。因此,如果文本仅包含单行,则它显示为垂直居中对齐。该对齐方式与我在它前面的相应标签不匹配。

例如:

enter image description here

这看起来很奇怪:(

有什么方法可以将标签文本设置为左上对齐吗?

最佳答案

这很容易做到。创建一个具有 verticalAlignment 属性的 UILabel 子类并覆盖 textRectForBounds:limitedToNumberOfLines 以返回顶部、中间或底部垂直对齐的正确边界。这是代码:

SOLabel.h

#import <UIKit/UIKit.h>

typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;

@interface SOLabel : UILabel

@property (nonatomic, readwrite) VerticalAlignment verticalAlignment;

@end

SOLabel.m

@implementation SOLabel

-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return nil;

// set inital value via IVAR so the setter isn't called
_verticalAlignment = VerticalAlignmentTop;

return self;
}

-(VerticalAlignment) verticalAlignment
{
return _verticalAlignment;
}

-(void) setVerticalAlignment:(VerticalAlignment)value
{
_verticalAlignment = value;
[self setNeedsDisplay];
}

// align text block according to vertical alignment settings
-(CGRect)textRectForBounds:(CGRect)bounds
limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect rect = [super textRectForBounds:bounds
limitedToNumberOfLines:numberOfLines];
CGRect result;
switch (_verticalAlignment)
{
case VerticalAlignmentTop:
result = CGRectMake(bounds.origin.x, bounds.origin.y,
rect.size.width, rect.size.height);
break;

case VerticalAlignmentMiddle:
result = CGRectMake(bounds.origin.x,
bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
rect.size.width, rect.size.height);
break;

case VerticalAlignmentBottom:
result = CGRectMake(bounds.origin.x,
bounds.origin.y + (bounds.size.height - rect.size.height),
rect.size.width, rect.size.height);
break;

default:
result = bounds;
break;
}
return result;
}

-(void)drawTextInRect:(CGRect)rect
{
CGRect r = [self textRectForBounds:rect
limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:r];
}

@end

关于iphone - 如何为 iOS 应用程序的 UILabel 设置左上对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7192088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com