UI 레이블 내에서 텍스트를 맨 위에 수직 정렬
나는 있습니다UILabel
두 줄의 텍스트를 위한 공간이 있습니다.텍스트가 너무 짧으면 레이블의 수직 중심에 이 텍스트가 표시되는 경우가 있습니다.
를 항상 맨 해야 ?UILabel
?
수직 정렬을 설정할 방법이 없습니다.UILabel
그러나 레이블의 프레임을 변경해도 동일한 효과를 얻을 수 있습니다.무슨 일이 일어나고 있는지 확실히 알 수 있도록 제 라벨을 주황색으로 만들었습니다.
이를 위한 빠르고 쉬운 방법은 다음과 같습니다.
[myLabel sizeToFit];
긴에는 둘이의줄만을더드는긴있텍는레경있우이는이블가트스상,경▁with,numberOfLines
0
(여기서 0은 줄 수에 제한이 없음을 의미합니다).
myLabel.numberOfLines = 0;
[myLabel sizeToFit];
긴 버전
무슨 일이 일어나고 있는지 볼 수 있도록 제 라벨을 코드로 만들겠습니다.이 대부분은 인터페이스 빌더에서도 설정할 수 있습니다.저의 설정은 포토샵으로 만든 배경 이미지로 마진(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];
레이블의 크기는 여전히 고정된 왼쪽 상단 모서리로 조정됩니다.한 후 블 의 너 설 같 수 있 할 습 니 다 정 다 과 음 고 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;
:sizeToFit
초기 레이블의 최소 너비를 준수합니다.만약 당신이 100 wide 라벨로 시작해서 전화를 한다면,sizeToFit
그 위에 폭이 100(또는 조금 더 작은)인 (거의 매우 높은) 라벨을 다시 제공합니다.크기를 조정하기 전에 레이블을 원하는 최소 너비로 설정할 수 있습니다.
기타 참고할 사항:
여부lineBreakMode
존중받는 것은 어떻게 설정하느냐에 달려 있습니다. NSLineBreakByTruncatingTail
은 (으)로 표시된 후에는 무시됩니다.sizeToFit
다른 두 가지 절단 모드(헤드 및 중간)와 마찬가지로. NSLineBreakByClipping
또한 무시됩니다. NSLineBreakByCharWrapping
평상시와 같이 작동합니다.프레임 폭은 여전히 가장 오른쪽 문자에 맞게 좁힙니다.
Mark Amery는 코멘트에서 자동 레이아웃을 사용하여 NIB와 스토리보드에 대한 수정을 제공했습니다.
이
view
에는 "ViewController"를 합니다.sizeToFit
로 불러들입니다.viewDidLoad
자동 레이아웃 크기를 지정하고 이후에 하위 뷰를 배치하기 때문에 작동하지 않습니다.viewDidLoad
호출되고 사용자의 호되고취소합의 합니다.sizeToFit
출호를 호출합니다. 그러나 호출.sizeToFit
에서.viewDidLayoutSubviews
효과가 있을 것입니다.
My Original Answer (후계/참고용):
이는 다음을 사용합니다.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"
을 합니다.
maximum number
으로 줄 바꿈:0°C(으):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 "];
아 때 문 추 가 모 된 새 공 필 추 요 합 니 다 이 간 가 에 라 인 이 든 폰 에 ▁i ▁is , phone ▁addition ▁added ▁new ▁because ▁space ▁every ▁needed 다 ▁in 니 요 합 필 이 공 간UILabels
returns는 무시되는 것 으)로 표시됩니다.
마찬가지로도 찬가지 alignBottom도 음과같이업데로 .@" \n@%"
신에를 "\n@%"
(사이클 초기화의 경우 "for(inti=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 alignTop];
또는[yourLabel alignBottom];
레이블 텍스트가 할당될 때마다 표시됩니다.
만약 누군가에게 도움이 된다면, 저도 같은 문제가 있었지만 사용에서 전환하여 문제를 해결할 수 있었습니다.UILabel
사용하기 위해UITextView
기능이 조금 다르기 때문에 모든 사람을 위한 것은 아니라는 점에 감사드립니다.
에는 사으우 용경는하를 사용합니다.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
무스, 오브젝티브-c, 소란 피우지 말고 스위프트 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)
}
}
스토리보드를 사용하는 가장 쉬운 접근 방식:
StackView에 레이블을 포함하고 Attribute Inspector에서 StackView의 다음 두 가지 특성을 설정합니다.
1-Axis
Horizontal
,
2-Alignment
Top
위의 답변처럼, 하지만 그것은 그다지 맞지 않거나 코드를 입력하기가 쉬워서 저는 그것을 좀 정리했습니다.이 확장명을 자체 .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];
이 작업을 수행하는 더 빠르고 더 더러운 방법은 UI 레이블의 줄 바꿈 모드를 "클립"으로 설정하고 고정된 양의 줄 바꿈을 추가하는 것입니다.
myLabel.lineBreakMode = UILineBreakModeClip;
myLabel.text = [displayString stringByAppendingString:"\n\n\n\n"];
이 솔루션이 모든 사람에게 적용되는 것은 아닙니다. 특히 문자열 끝에 "..."를 표시하려면 표시하는 줄 수를 초과하면 더 긴 코드 조각 중 하나를 사용해야 합니다. 하지만 대부분의 경우 이 솔루션을 사용하면 필요한 것을 얻을 수 있습니다.
에 에.UILabel
사용할 수 있습니다.UITextField
수직 정렬 옵션이 있습니다.
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.userInteractionEnabled = NO; // Don't allow interaction
저는 오랫동안 이 문제와 씨름해 왔고 저의 해결책을 공유하고 싶었습니다.
이것은 당신에게 줄 것입니다.UILabel
텍스트를 0.5 눈금까지 자동으로 축소하고 텍스트의 중심을 수직으로 맞춥니다.이한옵션은러board/ 스토리보드/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
인터페이스 작성기
- 트
UILabel
가능한 가장 큰 텍스트 크기로 - 트
Lines
Inspector의 은 '0'입니다.
당신의 코드에서
- 레이블의 텍스트 설정
- 러
sizeToFit
에.
코드 조각:
self.myLabel.text = @"Short Title";
[self.myLabel sizeToFit];
UI의 경우 (iOS8) 에서 UILabel의 합니다.noOfLines
및 =0' »
제약
UILabel 왼쪽 여백, 오른쪽 여백 및 위쪽 여백 제약 조건 조정.
Content Compression Resistance Priority For Vertical
1000' 세로로> 가로로.
편집:
noOfLines=0
다음과 같은 제약 조건은 원하는 결과를 얻기에 충분합니다.
제 앱에서 제가 한 일은 UILabel의 line 속성을 0으로 설정하고 UILabel의 하단 제약 조건을 만들고 아래 이미지와 같이 >= 0으로 설정되어 있는지 확인하는 것이었습니다.
사용하다textRect(forBounds:limitedToNumberOfLines:)
.
class TopAlignedLabel: UILabel {
override func drawText(in rect: CGRect) {
let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
super.drawText(in: textRect)
}
}
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
여기서 논의한 바와 같이.
저는 이 목적을 달성하기 위해 util 함수를 작성했습니다.확인할 수 있습니다.
다중 선 레이블의 높이를 조정하여 상단과 수직으로 정렬(void) Label With Top:(UILabel *) Label {CGsize maxSize = CGsizeMake(label.frame.size).폭, 999); label.fontSize를 FitWidth에 맞게 조정 = NO; 실제 높이를 보다CGSize 실제 크기 = [라벨].텍스트 크기WithFont:label.font 제약된 ToSize:maxSize lineBreakMode:label.lineBreakMode]; CGRectrect = label.frame;rect.size.height = 실제 크기.높이;label.frame = rect;}
어떻게 사용합니까?(IfblHello가 Interface Builder에 의해 생성되어 일부 UILabel 특성 세부사항을 건너뜁니다.)
lblHello.text = @"Hello World!헬로 월드!헬로 월드!헬로 월드!헬로 월드!헬로 월드!헬로 월드!헬로 월드!";lblHello.회선 수 = 5;[Label을 상단에 맞춤:lblHello];
저도 제 블로그에 기사로 썼습니다: http://fstoke.me/blog/ ?p=2819
소개 페이지의 코드뿐만 아니라 코드를 읽는 데 시간이 좀 걸렸는데, 기본 중앙 수직 정렬이 나타나지 않도록 라벨의 프레임 크기를 모두 수정하려고 한다는 것을 발견했습니다.
그러나 레이블에 텍스트가 너무 많은 경우(예: 동일한 높이의 여러 행)에도 레이블이 이러한 모든 공간을 차지하기를 원하는 경우가 있습니다.
저는 단순히 붙이는 것으로 했습니다. (로 저는 서단기, 라끝새에줄의벨참붙그것을이는해으기위결다사방습니다했용법여것은을상은받속른해하로실고제로제가것을로저는히순▁(▁▁(▁here▁i▁inheriteds▁thatpl▁it▁to▁i▁pad▁simplylines것▁to은,▁used▁an▁actually▁way▁solveative▁altern▁new▁by,은▁the받상여속기로▁note다고니▁of▁end실습로제▁label제서,가했사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 "];
}
여기서 제안을 받아 UIL 레이블을 감쌀 수 있고 크기를 조정하고 줄 수를 맨 위로 정렬되도록 설정하는 뷰를 만들었습니다.UI 레이블을 하위 뷰로 지정합니다.
@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
TTT Attributed Label을 사용할 수 있으며 수직 정렬을 지원합니다.
@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
.
저는 여러 줄, 최소 글꼴 크기, 그리고 부모 보기에서 수평과 수직으로 중심을 잡을 수 있는 레이블을 갖고 싶었습니다.레이블을 프로그래밍 방식으로 보기에 추가했습니다.
- (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
이 부품은 제가 직접 만든 것은 아니지만, 제가 자주 사용하는 부품이고 기능도 많고 잘 작동하는 것 같습니다.
위의 많은 방법을 사용했으며, 사용한 신속하고 더러운 접근 방식을 추가하고 싶습니다.
myLabel.text = [NSString stringWithFormat:@"%@\n\n\n\n\n\n\n\n\n",@"My label text string"];
문자열의 새 줄 수에 따라 사용 가능한 수직 공간이 텍스트로 채워지는지 확인하고, 오버플로 텍스트를 잘라내도록 UILabel을 설정합니다.
왜냐하면 때로는 충분히 좋은 것도 충분하기 때문입니다.
레이블 내부의 텍스트가 수직 중심에 있지 않기 때문에 이 문서를 읽는 모든 사용자를 위해 일부 글꼴 유형은 동일하게 설계되지 않았습니다.예를 들어, zapfino 크기가 16인 레이블을 만들면 텍스트가 수직으로 완벽하게 중심화되지 않은 것을 볼 수 있습니다.
그러나 헬베티카로 작업하면 텍스트가 수직으로 중앙에 배치됩니다.
하위 클래스 UILabel 및 다음과 같이 도면 직사각형을 구속합니다.
- (void)drawTextInRect:(CGRect)rect
{
CGSize sizeThatFits = [self sizeThatFits:rect.size];
rect.size.height = MIN(rect.size.height, sizeThatFits.height);
[super drawTextInRect:rect];
}
저는 새로운 라인 패딩과 관련된 솔루션을 시도해 보았는데, 경우에 따라 잘못된 동작에 부딪혔습니다., 으로 만드는 하는 것이 더 쉽습니다.numberOfLines
.
추신: 다음과 같은 방법으로 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];
}
자동 레이아웃을 사용하는 경우 수직 콘텐츠 설정HuggingPriority는 코드 또는 IB 중 하나로 1000입니다.IB에서 우선순위를 1로 설정한 다음 삭제하여 높이 제약 조건을 제거해야 할 수도 있습니다.
작업을 한, 은 작수을않지한수있사다니습용할는행복하를 사용할 수 있습니다.UITextView
에 UILabels
.
스크롤을 비활성화합니다.
텍스트를 완전히 표시하려면 사용자만 표시합니다.sizeToFit
그리고.sizeThatFits:
신속하게,
let myLabel : UILabel!
레이블의 텍스트를 화면에 맞게 만들고 맨 위에 표시하려면
myLabel.sizeToFit()
화면 너비 또는 특정 너비 크기에 맞게 레이블 글꼴을 만듭니다.
myLabel.adjustsFontSizeToFitWidth = YES
및 레이블에 대한 일부 텍스트Alignment:
myLabel.textAlignment = .center
myLabel.textAlignment = .left
myLabel.textAlignment = .right
myLabel.textAlignment = .Natural
myLabel.textAlignment = .Justified
이것은 오래된 솔루션입니다. 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
언급URL : https://stackoverflow.com/questions/1054558/vertically-align-text-to-top-within-a-uilabel
'source' 카테고리의 다른 글
Git 저장소를 이전 커밋으로 되돌리려면 어떻게 해야 합니까? (0) | 2023.05.04 |
---|---|
스타일/템플릿을 사용하여 소수 자릿수를 wpf 형식으로 지정하는 방법은 무엇입니까? (0) | 2023.05.04 |
로컬로 생성된 스크립트를 원격 서명 실행 정책에서 실행할 수 없는 이유는 무엇입니까? (0) | 2023.05.04 |
VB를 사용하여 Excel 워크시트를 파일 이름+워크시트 이름으로 CSV 파일에 저장 (0) | 2023.05.04 |
Postgres/SQL에서 두 정수의 최소값/max를 얻는 방법은 무엇입니까? (0) | 2023.05.04 |