简体   繁体   English

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

[英]How to set top-left alignment for UILabel for iOS application?

I have added one label in my nib file, then its required to have top-left alignment for that lable.我在我的 nib 文件中添加了一个标签,然后它需要对该标签进行左上对齐。 As I am providing text at runtime so its not sure that how much lines there are.由于我在运行时提供文本,因此不确定有多少行。 So if text contains only single line then it appears as vertical-center aligned.因此,如果文本仅包含单行,则它显示为垂直居中对齐。 That alignment is not matching with my respective lable in front of it.该对齐方式与我前面的相应标签不匹配。

For example:例如:

在此处输入图像描述

Which is looking odd :(这看起来很奇怪:(

Is there any way where i can set label text proper to Top-Left alignment?有什么方法可以将标签文本设置为左上对齐?

It's fairly easy to do.这很容易做到。 Create a UILabel sublcass with a verticalAlignment property and override textRectForBounds:limitedToNumberOfLines to return the correct bounds for a top, middle or bottom vertical alignment.使用verticalAlignment属性创建一个UILabel子类并覆盖textRectForBounds:limitedToNumberOfLines以返回顶部、中间或底部垂直对齐的正确边界。 Here's the code:这是代码:

SOLabel.h 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 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

Rather than re-explaining, I will link to this rather extensive & highly rated question/answer:我不会重新解释,而是链接到这个相当广泛且评价很高的问题/答案:

Vertically align text to top within a UILabel 在 UILabel 中将文本垂直对齐到顶部

The short answer is no, Apple didn't make this easy, but it is possible by changing the frame size.简短的回答是否定的,Apple 并没有让这变得容易,但可以通过改变框架大小来实现。

I found a solution using AutoLayout in StoryBoard.我在 StoryBoard 中找到了使用 AutoLayout 的解决方案。

1) Set no of lines to 0 and text alignment to Left. 1) 将行数设置为 0,将文本对齐方式设置为左。

在此处输入图像描述

2) Set height constraint. 2) 设置高度约束。

在此处输入图像描述

3) The height Constraint should be in Relation - Less Than or Equal 3)高度约束应该是相关的 - 小于或等于

在此处输入图像描述

4) 4)

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

I got the result as follows :我得到的结果如下:

在此处输入图像描述

The SOLabel works for me. SOLabel 对我有用。

Swift 3 & 5:斯威夫特 3 和 5:

This version has been updated from the original to allow support for RTL languages:此版本已从原始版本更新,以支持 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)
    }
}

Swift 1:斯威夫特 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)
    }
}

In my case, it was bottom space constraint issue.就我而言,这是bottom space限制问题。 I had set it to = 16 .我已将其设置为= 16

When I set it to bottom to >= 16 , this issue got solved.当我将其设置为bottom to >= 16时,这个问题得到了解决。

Also, if you have any height constraint in the label, then you need to remove it.此外,如果标签中有任何高度限制,则需要将其删除。

Here's my label's constraint view in the size inspector:这是我在尺寸检查器中的标签约束视图:

约束

In your code在您的代码中

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

Beware that if you use that in table cells or other views that get recycled with different data, you'll need to store the original frame somewhere and reset it before calling sizeToFit.请注意,如果您在表格单元格或其他使用不同数据回收的视图中使用它,您需要将原始框架存储在某处并在调用 sizeToFit 之前将其重置。

I found another solution for the same problem.我为同样的问题找到了另一种解决方案。 I used UITextView instead of UILabel and switched editable() function to false .我使用UITextView而不是UILabel并将editable()函数切换为false

I was also having this problem but what I found was the the order in which you set the UILabel's properties and methods matters!我也遇到了这个问题,但我发现设置 UILabel 的属性和方法的顺序很重要!

If you call [label sizeToFit] before label.font = [UIFont fontWithName:@"Helvetica" size:14];如果在label.font = [UIFont fontWithName:@"Helvetica" size:14];之前调用[label sizeToFit] ]; then the text does not align to the top but if you swap them around then it does!那么文本不会与顶部对齐,但如果你交换它们,它就会对齐!

I also noticed that setting the text first makes a difference too.我还注意到,首先设置文本也会有所不同。

Hope this helps.希望这可以帮助。

As you are using the interface builder, set the constraints for your label (be sure to set the height and width as well).当您使用界面构建器时,请为您的标签设置约束(请务必同时设置高度和宽度)。 Then in the Size Inspector, check the height for the label.然后在尺寸检查器中,检查标签的高度。 There you will want it to read >= instead of =.在那里你会希望它读 >= 而不是 =。 Then in the implementation for that view controller, set the number of lines to 0 (can also be done in IB) and set the label [label sizeToFit];然后在该视图控制器的实现中,将行数设置为 0(也可以在 IB 中完成)并设置标签 [label sizeToFit]; and as your text gains length, the label will grow in height and keep your text in the upper left.随着您的文本长度增加,标签的高度会增加,并将您的文本保持在左上角。

If what you need is non-editable text that by default starts at the top left corner you can simply use a Text View instead of a label and then set its state to non-editable, like this:如果您需要的是默认从左上角开始的不可编辑文本,您可以简单地使用文本视图而不是标签,然后将其状态设置为不可编辑,如下所示:

textview.isEditable = false

Way easier than messing with the labels...比弄乱标签容易得多...

Cheers!干杯!

Solution with SoLabel works , Thanks.使用 Solabel 的解决方案有效,谢谢。

Bellow I have added monotouch version:贝娄我添加了单点触控版本:

    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
}

最简单和最简单的方法是在 StackView 中嵌入 Label 并将 StackView 的 Axis 设置为 Horizo​​ntal,Alignment to Top 在 Storyboard 的 Attribute Inspector 中,如下所示

Building on top of totiG's awesome answer, I have created an IBDesignable class that makes it extremely easy to customize a UILabel's vertical alignment right from the StoryBoard.在 totiG 的出色答案之上,我创建了一个 IBDesignable 类,它可以非常容易地从 StoryBoard 自定义 UILabel 的垂直对齐方式。 Just make sure that you set your UILabel's class to 'VerticalAlignLabel' from the StoryBoard identity inspector.只需确保从 StoryBoard 身份检查器中将 UILabel 的类设置为“VerticalAlignLabel”。 If the vertical alignment doesn't take effect, go to Editor->Refresh All Views which should do the trick.如果垂直对齐没有生效,请转到 Editor->Refresh All Views 这应该可以解决问题。

How it works: Once you set your UILabel's class correctly, the storyboard should show you an input field that takes an integer (alignment code).它是如何工作的:一旦你正确设置了你的 UILabel 的类,故事板应该会显示一个输入字段,它需要一个整数(对齐代码)。

Update: I've added support for centered labels ~Sev更新:我添加了对居中标签的支持~Sev


Enter 0 for Top Alignment为顶部对齐输入 0

Enter 1 for Middle Alignment为中间对齐输入 1

Enter 2 for Bottom Alignment输入 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) } }

您也可以将您的 UILabel 更改为 UITextView,因为它们基本上做同样的事情,除了 UITextView 的优点是文本自动对齐到左上角

Use UITextView instead of UILabel .使用UITextView而不是UILabel Also it works for UITableViewCell width automatic row height它也适用于 UITableViewCell 宽度自动行高

Set isScrollEnabled and isEditable to false .isScrollEnabledisEditable设置为false Add min height constraint for TextView为 TextView 添加最小高度约束

One line text screenshot一行文字截图

Multiline text screenshot多行文字截图

final class TestVC: UIViewController {
    
    lazy var testTextLabel: UITextView = {
        $0.isScrollEnabled = false
        $0.isEditable = false
        
        $0.font = .systemFont(ofSize: 17, weight: .medium)
        $0.textColor = .black
        
        $0.layer.borderWidth = 1
        $0.layer.borderColor = UIColor.black.cgColor
        $0.layer.cornerRadius = 5
        
        return $0
    }(UITextView())
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        testTextLabel.text = "Your text"
        
        view.addSubview(testTextLabel)
        testTextLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            testTextLabel.topAnchor.constraint(equalTo: testTextLabel.superview!.safeAreaLayoutGuide.topAnchor, constant: 12),
            testTextLabel.leadingAnchor.constraint(equalTo: testTextLabel.superview!.leadingAnchor, constant:  12),
            testTextLabel.widthAnchor.constraint(equalToConstant: 250),
            testTextLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 70)
        ])
    }
}

Swift 3 version of @totiG's answer @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)
    }
}

我有这个问题,但我的标签在UITableViewCell中,而且解决问题的最简单方法是创建一个空的UIView并将标签设置在其中,并且仅在顶部和左侧进行约束,关闭诅咒将行数设置为 0

@totiG's answer is correct and solved my problem. @totiG 的回答是正确的,解决了我的问题。 But I found a problem while implementing this method, in smaller devices like 5s , SE, this doesn't work for me.但是我在实施这种方法时发现了一个问题,在 5s 、 SE 等较小的设备中,这对我不起作用。 I have to set label.sizeToFit() in override func layoutSubViews()我必须在override func layoutSubViews()中设置label.sizeToFit() )

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

Use textRect(forBounds:limitedToNumberOfLines:)使用 textRect(forBounds:limitedToNumberOfLines:)

class TopAlignedLabel: UILabel {
      override func drawText(in rect: CGRect) {
        let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        super.drawText(in: textRect)
      }
}

For iOS 7 that's what i made and worked for me对于 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];
}

Swift 2.0: : Using UILabel Extension Swift 2.0: : 使用 UILabel 扩展

Make constant enum values in a empty Swift file.在一个空的 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"

}

Using UILabel Extension:使用 UILabel 扩展:

Make a empty Swift class and name it.创建一个空的 Swift 类并为其命名。 Add the following.添加以下内容。

//  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!

     }
    }

Usage :用法 :

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

Swift 5斯威夫特 5

It´s simple, the order of the properties is everything.很简单,属性的顺序就是一切。

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)

I was able to fix it by embedding the tag within a view.我能够通过在视图中嵌入标签来修复它。 It worked perfect!效果很好!

解决方法:在视图中嵌入标签

You need to set in layoutSubviews:你需要在layoutSubviews中设置:

override func layoutSubviews() {
   super.layoutSubviews()
   yourLabel.sizeToFit()
   //yourLabel.center.x = someView.center.x // optionally if exists
}

Pure Storyboard solution...纯故事板解决方案...

Horizontal left alignment is easy since it can be setup as UILabel property in Interface Builder.水平左对齐很容易,因为它可以在 Interface Builder 中设置为 UILabel 属性。

Vertical top alignment can be setup with just two constraints:只需两个约束即可设置垂直顶部对齐:

  1. one that setups UILabel.bottom as greater or equal to some other view (maximal height) with priority like 1000 (required).一个将 UILabel.bottom 设置为greater or equal其他视图(最大高度),优先级为 1000(必需)的视图。 This will add UILabel ability to grow up to this constraint's height这将增加 UILabel 成长到这个约束的高度的能力

  2. other that setups UILabel.bottom like equal 0 (minimal height) with priority like 750 (non-required).其他将 UILabel.bottom 设置为equal 0(最小高度),优先级为 750(非必需)。 This will add UILabel ability/tendency to shrink to minimal size allowed by its content这将增加 UILabel 能力/倾向于缩小到其内容允许的最小尺寸

This means that UIKit will try to setup UILabel height as minimal as possible in range from minimal auto-sized UILabel based on its properties/content (text, font, ...) up to 1. constraint height.这意味着 UIKit 将尝试将 UILabel 高度设置为尽可能小,范围从基于其属性/内容(文本、字体、...)的最小自动调整 UILabel 到 1. 约束高度。

How to set top-left alignment for UILabel for iOS application?如何为 iOS 应用程序的 UILabel 设置左上对齐? Label Set Content Mode to "Top Left" work for me, thank you very much:标签集内容模式为“左上角”对我有用,非常感谢:
如何为 iOS 应用程序的 UILabel 设置左上对齐?标签设置内容模式为“左上”对我有用,非常感谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM