iOS 애플리케이션 용 UILabel의 왼쪽 상단 정렬을 설정하는 방법은 무엇입니까?


99

내 펜촉 파일에 레이블 하나를 추가 한 다음 해당 레이블에 대해 왼쪽 상단 정렬이 필요합니다. 런타임에 텍스트를 제공하므로 얼마나 많은 줄이 있는지 확실하지 않습니다. 따라서 텍스트에 한 줄만 포함되어 있으면 세로 중앙 정렬로 나타납니다. 그 정렬은 그 앞에있는 내 각 레이블과 일치하지 않습니다.

예를 들면 :

여기에 이미지 설명 입력

이상하게 보입니다 :(

레이블 텍스트를 왼쪽 위 정렬에 맞게 설정할 수있는 방법이 있습니까?


답변:



64

매우 쉽습니다. 크리에이트 UILabelA를 sublcass verticalAlignment속성을 재정의 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

3
나는 또한이 솔루션을 실행하기 전에 여기에서 다른 많은 솔루션을 시도했습니다. 완벽하게 작동했습니다! StoryBoard에서이 작업을 수행하는 경우에는 CustomClass 속성을 유틸리티 검사기에서 UILabel 대신 SOLabel (또는 이름을 지정하기로 결정한 이름)으로 설정해야합니다.
— TMc 2014 년

이것은 매우 도움이됩니다. 감사합니다. 중앙 또는 오른쪽 정렬 텍스트에서는 작동하지 않지만 in bounds.size.width대신 사용 하면 문제가 해결되는 것 같습니다. rect.size.widthtextRectForBounds:limitedToNumberOfLines:
— Geoff Hackworth 2015 년

1
iOS 9 Xcode 7에서 'Thread 1 : EXC_BAD_ACCESS (Code 2, address = 0x ...)'가 발생한 경우 setter와 getter를 제거하기 만하면됩니다.-(VerticalAlignment) verticalAlignment; 및-(void) setVerticalAlignment : (VerticalAlignment) value 함수, 변수가 @property이기 때문입니다. 합성되고 접근자를 포함합니다.
— felixwcf

여기 메서드에서 몇 가지 수정 사항이 있습니다. "textRectForBounds"-result = CGRectMake (rect.origin.x, bounds.origin.y, rect.size.width, rect.size.height); rightAlignment UILable에 대한 내 작품을 만들기 위해.
— g212gs

50

StoryBoard에서 AutoLayout을 사용하는 솔루션을 찾았습니다.

1) 줄 수를 0으로, 텍스트 정렬을 왼쪽으로 설정합니다.

여기에 이미지 설명 입력

2) 높이 제한을 설정합니다.

여기에 이미지 설명 입력

3) 높이 제약은 관계식이어야합니다-작거나 같음

여기에 이미지 설명 입력

4)

   override func viewWillLayoutSubviews() {
        sampleLabel.sizeToFit()
    }

결과는 다음과 같습니다.

여기에 이미지 설명 입력


2
재사용이 가능한 UITableViewCell에서도 매력처럼 작동합니다.
— alex.bour

당신은 배치합니까 viewWillLayoutSubviews컨트롤러 또는 셀 파일에? 컨트롤러 인 경우 셀에서 UILabel에 어떻게 액세스합니까?
— Craig.Pearce

4 단계는 어디에 두나요? 새로운 사용자로서 저는 순수한 UI 솔루션을 갖게되어 기뻤습니다. 그러면 해당 코드가 갑자기 나오고 어디에
— 넣을지

SampleClass.swift 또는 SampleTableViewCell.swift
— AG

이것이 해결책이어야합니다. 완벽하게 작동하며 해킹이나 서브 클래 싱이 필요하지 않습니다.
— Curious101

44

SOLabel이 저에게 효과적입니다.

Swift 3 및 5 :

이 버전은 RTL 언어를 지원하도록 원본에서 업데이트되었습니다.

public class VerticalAlignLabel: UILabel {
    enum VerticalAlignment {
        case top
        case middle
        case bottom
    }

    var verticalAlignment : VerticalAlignment = .top {
        didSet {
            setNeedsDisplay()
        }
    }

    override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
        let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)

        if UIView.userInterfaceLayoutDirection(for: .unspecified) == .rightToLeft {
            switch verticalAlignment {
            case .top:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
            case .middle:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
            case .bottom:
                return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
            }
        } else {
            switch verticalAlignment {
            case .top:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
            case .middle:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
            case .bottom:
                return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
            }
        }
    }

    override public func drawText(in rect: CGRect) {
        let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: r)
    }
}

스위프트 1 :

class UIVerticalAlignLabel: UILabel {

enum VerticalAlignment : Int {
    case VerticalAlignmentTop = 0
    case VerticalAlignmentMiddle = 1
    case VerticalAlignmentBottom = 2
}

var verticalAlignment : VerticalAlignment = .VerticalAlignmentTop {
    didSet {
        setNeedsDisplay()
    }
}

required init(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
}

override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
    let rect = super.textRectForBounds(bounds, limitedToNumberOfLines: limitedToNumberOfLines)

    switch(verticalAlignment) {
        case .VerticalAlignmentTop:
            return CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height)
        case .VerticalAlignmentMiddle:
            return CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height) / 2, rect.size.width, rect.size.height)
        case .VerticalAlignmentBottom:
            return CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height), rect.size.width, rect.size.height)
        default:
            return bounds
    }
}

override func drawTextInRect(rect: CGRect) {
    let r = self.textRectForBounds(rect, limitedToNumberOfLines: self.numberOfLines)
    super.drawTextInRect(r)
    }
}

이 코드를 사용하여 레이블을 만들려고하면 : var myLabel = VerticalAlignLabel () "호출시 'coder'매개 변수에 대한 인수가 없습니다."가 표시됩니다. 이 VerticalAlignLabel 하위 클래스를 사용하여 레이블을 어떻게 만들 수 있습니까?
— RanLearns

1
지금 Swift 버전 3을 사용해보세요-필요하지 않은 필수 초기화가 있습니다.
— totiG

14

제 경우에는 bottom space제약 문제였습니다. 나는 그것을로 설정했다 = 16.

로 설정하면 bottom to >= 16이 문제가 해결되었습니다.

또한 레이블에 높이 제약이있는 경우이를 제거해야합니다.

크기 검사기에서 내 레이블의 제약보기는 다음과 같습니다.

강제


레이블을 선택할 때 제약 옵션이 없습니다.
— velkoon

가장 간단한 수정-제약 조건과 자동 레이아웃이 처리하도록합니다. 감사!
— Jason

13

귀하의 코드에서

label.text = @"some text";
[label sizeToFit];

다른 데이터로 재활용되는 테이블 셀이나 다른 뷰에서이를 사용하는 경우 원본 프레임을 어딘가에 저장하고 sizeToFit을 호출하기 전에 재설정해야합니다.


이 시점에서 실제로 모든 것을 자동 레이아웃에 남겨 두는 것이 좋습니다. 더 이상 필요하지 않습니다.
— n13

9

같은 문제에 대한 다른 해결책을 찾았습니다. UITextView대신 사용 UILabel하고 editable()기능을 false.


@geekyaleks 왜 이것이 멍청한 해킹입니까? 괜찮은 해결 방법처럼 보이지만 질문에 대한 직접적인 대답이 아닌 것 외에 다른 문제가 있습니까?
— Christopher Larsen

작업에 적절한 UI 구성 요소를 사용하지 않기 때문에 적절하지 않습니다. 수직 정렬과 같은 단순한 것에 대한 타협이되어서는 안됩니다. 작업에 적합한 구성 요소를 사용해야합니다. 다른 건 ... 해킹입니다
— geekyaleks

7

나는 또한이 문제가 있었지만 UILabel의 속성과 메서드를 설정하는 순서가 중요하다는 것을 발견했습니다!

[label sizeToFit]이전에 전화 label.font = [UIFont fontWithName:@"Helvetica" size:14];하면 텍스트가 상단에 정렬되지 않지만 교체하면 텍스트가 정렬됩니다!

또한 텍스트를 먼저 설정하는 것도 차이가 있다는 것을 알았습니다.

도움이 되었기를 바랍니다.


큰. sizeToFit ()는 마지막에 호출되어야합니다.
— MKatleast3

4

인터페이스 빌더를 사용할 때 레이블에 대한 제약 조건을 설정합니다 (높이와 너비도 설정해야 함). 그런 다음 크기 검사기에서 레이블의 높이를 확인합니다. 거기에서 = 대신> =를 ​​읽고 싶을 것입니다. 그런 다음 해당 뷰 컨트롤러의 구현에서 줄 수를 0으로 설정하고 (IB에서도 수행 할 수 있음) 레이블 [label sizeToFit]를 설정합니다. 텍스트의 길이가 늘어 나면 레이블의 높이가 커지고 텍스트는 왼쪽 상단에 유지됩니다.


4

필요한 것이 기본적으로 왼쪽 상단 모서리에서 시작하는 편집 불가능한 텍스트 인 경우 레이블 대신 텍스트보기를 사용하고 다음과 같이 상태를 편집 불가능으로 설정할 수 있습니다.

textview.isEditable = false

라벨을 엉망으로 만드는 것보다 훨씬 쉽습니다 ...

건배!


3

SoLabel의 솔루션이 작동합니다. 감사합니다.

Bellow 모노 터치 버전을 추가했습니다.

    public class UICustomLabel : UILabel
{
    private UITextVerticalAlignment _textVerticalAlignment;

    public UICustomLabel()
    {
        TextVerticalAlignment = UITextVerticalAlignment.Top;
    }

    public UITextVerticalAlignment TextVerticalAlignment
    {
        get
        {
            return _textVerticalAlignment;
        }
        set
        {
            _textVerticalAlignment = value;
            SetNeedsDisplay();
        }
    }

    public override void DrawText(RectangleF rect)
    {
        var bound = TextRectForBounds(rect, Lines);
        base.DrawText(bound);
    }

    public override RectangleF TextRectForBounds(RectangleF bounds, int numberOfLines)
    {
        var rect = base.TextRectForBounds(bounds, numberOfLines);
        RectangleF resultRect;
        switch (TextVerticalAlignment)
        {
            case UITextVerticalAlignment.Top:
                resultRect = new RectangleF(bounds.X, bounds.Y, rect.Size.Width, rect.Size.Height);
                break;
            case UITextVerticalAlignment.Middle:
                resultRect = new RectangleF(bounds.X,
                                            bounds.Y + (bounds.Size.Height - rect.Size.Height)/2,
                                            rect.Size.Width, rect.Size.Height);
                break;
            case UITextVerticalAlignment.Bottom:
                resultRect = new RectangleF(bounds.X,
                                            bounds.Y + (bounds.Size.Height - rect.Size.Height),
                                            rect.Size.Width, rect.Size.Height);
                break;

            default:
                resultRect = bounds;
                break;
        }

        return resultRect;
    }
}

public enum UITextVerticalAlignment
{
    Top = 0, // default
    Middle,
    Bottom
}


2

totiG의 멋진 답변을 바탕으로 StoryBoard에서 바로 UILabel의 수직 정렬을 매우 쉽게 사용자 지정할 수있는 IBDesignable 클래스를 만들었습니다. StoryBoard ID 검사기에서 UILabel의 클래스를 'VerticalAlignLabel'로 설정했는지 확인하십시오. 수직 정렬이 적용되지 않으면 편집기-> 모든보기 새로 고침으로 이동하여 트릭을 수행해야합니다.

작동 방식 : UILabel의 클래스를 올바르게 설정하면 스토리 보드에 정수 (정렬 코드)를 사용하는 입력 필드가 표시됩니다.

업데이트 : 중앙 레이블 ~ Sev에 대한 지원을 추가했습니다.


상단 정렬에 0을 입력합니다.

중간 정렬에 1을 입력합니다.

하단 정렬에 2를 입력합니다.

    @IBDesignable class VerticalAlignLabel: UILabel {
    
    @IBInspectable var alignmentCode: Int = 0 {
        didSet {
            applyAlignmentCode()
        }
    }
    
    func applyAlignmentCode() {
        switch alignmentCode {
        case 0:
            verticalAlignment = .top
        case 1:
            verticalAlignment = .topcenter
        case 2:
            verticalAlignment = .middle
        case 3:
            verticalAlignment = .bottom
        default:
            break
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.applyAlignmentCode()
    }
    
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        
        self.applyAlignmentCode()
    }
    
    enum VerticalAlignment {
        case top
        case topcenter
        case middle
        case bottom
    }
    
    var verticalAlignment : VerticalAlignment = .top {
        didSet {
            setNeedsDisplay()
        }
    }
    
    override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
        let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)
        
        if #available(iOS 9.0, *) {
            if UIView.userInterfaceLayoutDirection(for: .unspecified) == .rightToLeft {
                switch verticalAlignment {
                case .top:
                    return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
                case .topcenter:
                    return CGRect(x: self.bounds.size.width - (rect.size.width / 2), y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
                case .middle:
                    return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
                case .bottom:
                    return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
                }
            } else {
                switch verticalAlignment {
                case .top:
                    return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
                case .topcenter:
                    return CGRect(x: (self.bounds.size.width / 2 ) - (rect.size.width / 2), y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
                case .middle:
                    return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
                case .bottom:
                    return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
                }
            }
        } else {
            // Fallback on earlier versions
            return rect
        }
    }
    
    override public func drawText(in rect: CGRect) {
        let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: r)
    }
}


2

UITextView의 장점은 텍스트가 자동으로 왼쪽 상단에 정렬된다는 점을 제외하면 기본적으로 동일한 작업을 수행하기 때문에 UILabel을 UITextView로 변경할 수도 있습니다.


1

나는이 문제가 있지만 내 레이블은 UITableViewCell에 있었고 기금에서 문제를 해결하는 가장 쉬운 방법은 빈 UIView를 만들고 그 안에 제약 조건이있는 레이블을 상단과 왼쪽에만 설정하는 것이 었습니다. 줄 수를 0으로 설정


0

iOS 7의 경우 내가 만들고 일한 것입니다.

@implementation UILabel (VerticalAlign)
- (void)alignTop
{
    CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
    NSDictionary *attributes = @{NSFontAttributeName : self.font};
    CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                              attributes:attributes
                                                 context:nil];
    int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);

    CGRect newFrame = self.frame;
    newFrame.size.height = numberOfLines * self.font.lineHeight;
    self.frame = newFrame;
}

- (void)alignBottom
{
    CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
    NSDictionary *attributes = @{NSFontAttributeName : self.font};
    CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                            attributes:attributes
                                               context:nil];
    int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);

    int numberOfNewLined = (self.frame.size.height/self.font.lineHeight) - numberOfLines;

    NSMutableString *newLines = [NSMutableString string];
    for(int i=0; i< numberOfNewLined; i++){
        [newLines appendString:@"\n"];
    }
    [newLines appendString:self.text];
    self.text = [newLines mutableCopy];
}

0

Swift 2.0 : : UILabel 확장 사용

빈 Swift 파일에서 상수 열거 형 값을 만드십시오.

//  AppRef.swift

import UIKit
import Foundation

enum UILabelTextPositions : String {

 case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
 case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
 case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"

}

UILabel 확장 사용 :

빈 Swift 클래스를 만들고 이름을 지정합니다. 다음을 추가하십시오.

//  AppExtensions.swift

import Foundation
import UIKit

    extension UILabel{ 
     func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
     {
      let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)

      switch positionIdentifier
      {
      case "VerticalAlignmentTop":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
       break;

      case "VerticalAlignmentMiddle":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
        rect.size.width, rect.size.height);
       break;

      case "VerticalAlignmentBottom":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
       break;

      default:
       sampleLabel!.frame = bounds;
       break;
      }
      return sampleLabel!

     }
    }

사용법 :

myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)

무엇이 필요한지 설명해 주 sampleLabel: UILabel?시겠습니까?
— Craig.Pearce

이 func makeLabelTextPosition (sampleLabel : UILabel ?, positionIdentifier : String) {}에서 UILabel 객체를 전달해야합니다.
— AG

0

@totiG의 답변의 Swift 3 버전

class UIVerticalAlignLabel: UILabel {
    enum VerticalAlignment : Int {
        case VerticalAlignmentTop = 0
        case VerticalAlignmentMiddle = 1
        case VerticalAlignmentBottom = 2
    }

    @IBInspectable var verticalAlignment : VerticalAlignment = .VerticalAlignmentTop {
        didSet {
            setNeedsDisplay()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
        let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)

        switch(verticalAlignment) {
        case .VerticalAlignmentTop:
            return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
        case .VerticalAlignmentMiddle:
            return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
        case .VerticalAlignmentBottom:
            return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
        }
    }

    override func drawText(in rect: CGRect) {
        let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
        super.drawText(in: r)
    }
}

0

@totiG의 대답이 정확하고 내 문제를 해결했습니다. 그러나이 방법을 구현하는 동안 5s, SE와 같은 작은 장치에서 문제가 발견되었습니다. 나는 세트가 label.sizeToFit()에override func layoutSubViews()

override func layoutSubViews() {
    super.layoutSubViews()
    // Do other works if needed
    label.sizeToFit()
}

0

스위프트 5

간단합니다. 속성의 순서가 전부입니다.

titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 291.2)
titleLabel.backgroundColor = UIColor.clear //set a light color to see the frame
titleLabel.textAlignment = .left
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.numberOfLines = 4
titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 35)
titleLabel.text = "Example"
titleLabel.sizeToFit()
self.view.addSubview(titleLabel)

-2

iOS 애플리케이션 용 UILabel의 왼쪽 상단 정렬을 설정하는 방법은 무엇입니까? 콘텐츠 모드를 "왼쪽 상단"으로 레이블 설정하면 저에게 효과적입니다. 감사합니다.
iOS 애플리케이션 용 UILabel의 왼쪽 상단 정렬을 설정하는 방법은 무엇입니까?  레이블 설정 콘텐츠 모드를 "왼쪽 상단"으로 설정하는 것이 좋습니다. 감사합니다.


1
나를 위해 아무것도하지 않습니다. 이것은 직관적으로 그것이 해결책이어야하는 것처럼 보였기 때문에 그것이 작동하지 않을 때 (또는 그 문제에 대해 겉보기에 잭을 다하는 것 같았을 때) Google을 선택한 이유입니다.
— velkoon
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.