103

nibファイルに1つのラベルを追加しました。次に、そのラベルを左上に配置する必要があります。実行時にテキストを提供しているので、行数がわかりません。したがって、テキストに1行しか含まれていない場合は、垂直方向に中央揃えで表示されます。その配置は、その前にある私のそれぞれのラベルと一致していません。

例えば:

ここに画像の説明を入力してください

奇妙に見えます:(

ラベルテキストを左上揃えに適切に設定する方法はありますか?

4

25 に答える 25

65

かなり簡単です。プロパティとオーバーライドを使用してUILabelサブクラスを作成し、上、中、または下の垂直方向の配置の正しい境界を返します。コードは次のとおりです。verticalAlignmenttextRectForBounds: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
于 2011-08-26T17:22:52.973 に答える
63

再説明するのではなく、このかなり広範で評価の高い質問/回答にリンクします。

UILabel内でテキストを上に垂直に配置します

簡単な答えはノーです。Appleはこれを簡単にしませんでしたが、フレームサイズを変更することで可能になります。

于 2011-08-25T14:30:21.620 に答える
55

StoryBoardでAutoLayoutを使用した解決策を見つけました。

1)行数を0に設定し、テキストの配置を左に設定します。

ここに画像の説明を入力してください

2)高さ制約を設定します。

ここに画像の説明を入力してください

3)高さの制約は次の関係にある必要があります-以下

ここに画像の説明を入力してください

4)

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

次のような結果が得られました:

ここに画像の説明を入力してください

于 2016-04-01T07:43:02.243 に答える
51

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)
    }
}
于 2014-11-23T19:46:20.370 に答える
23

私の場合、それはbottom space制約の問題でした。に設定しました= 16

に設定するとbottom to >= 16、この問題は解決しました。

また、ラベルに高さの制約がある場合は、それを削除する必要があります。

サイズインスペクターでのラベルの制約ビューは次のとおりです。

制約

于 2018-07-28T12:35:08.587 に答える
14

あなたのコードで

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

これをテーブルセルや別のデータでリサイクルされる他のビューで使用する場合は、sizeToFitを呼び出す前に、元のフレームをどこかに保存してリセットする必要があることに注意してください。

于 2012-03-10T17:37:07.543 に答える
9

同じ問題の別の解決策を見つけました。UITextView代わりに使用し、機能をにUILabel切り替えました。editable()false

于 2015-03-23T04:45:08.160 に答える
8

私もこの問題を抱えていましたが、UILabelのプロパティとメソッドを設定する順序が重要であることがわかりました。

[label sizeToFit]以前に電話をかけた場合label.font = [UIFont fontWithName:@"Helvetica" size:14];、テキストは上に揃えられませんが、入れ替えると、揃えられます。

また、最初にテキストを設定すると違いが生じることにも気づきました。

お役に立てれば。

于 2013-11-20T12:27:55.793 に答える
5

Interface Builderを使用しているので、ラベルの制約を設定します(高さと幅も必ず設定してください)。次に、サイズインスペクターで、ラベルの高さを確認します。そこでは、=の代わりに>=を読み取る必要があります。次に、そのView Controllerの実装で、行数を0に設定し(IBでも実行可能)、ラベル[labelsizeToFit]を設定します。テキストの長さが長くなると、ラベルの高さが増し、テキストが左上に表示されます。

于 2015-01-27T21:11:48.170 に答える
4

必要なのがデフォルトで左上隅から始まる編集不可能なテキストである場合は、ラベルの代わりにテキストビューを使用して、次のようにその状態を編集不可能に設定できます。

textview.isEditable = false

ラベルをいじるよりもずっと簡単です...

乾杯!

于 2017-11-10T16:42:01.497 に答える
3

SoLabelを使用したソリューションは機能します、ありがとう。

ベロー私はモノタッチバージョンを追加しました:

    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
}
于 2014-06-02T09:18:04.017 に答える
3

最も簡単で簡単な方法は、StackViewにラベルを埋め込み、ここに示すように、ストーリーボードの属性インスペクターでStackViewの軸を水平に設定し、位置合わせを上に設定することです。

于 2017-03-28T11:30:16.980 に答える
2

totiGのすばらしい答えに基づいて、ストーリーボードからUILabelの垂直方向の配置を非常に簡単にカスタマイズできるIBDesignableクラスを作成しました。StoryBoardIDインスペクターからUILabelのクラスを「VerticalAlignLabel」に設定していることを確認してください。垂直方向の配置が有効にならない場合は、[エディター]->[すべてのビューを更新]に移動します。

仕組み:UILabelのクラスを正しく設定すると、ストーリーボードに整数(配置コード)を受け取る入力フィールドが表示されます。

更新:中央に配置されたラベルのサポートを追加しました〜Sev


上揃えに0を入力します

MiddleAlignmentに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)
    }
}

于 2018-03-01T12:19:02.913 に答える
2

UILabelをUITextViewに変更することもできます。これは、UITextViewの利点がテキストが自動的に左上に配置されることを除いて、基本的に同じことを行うためです。

于 2019-01-17T12:07:03.563 に答える
2

UILabelの代わりにUITextViewを使用します。また、UITableViewCellの幅の自動行の高さでも機能します

isScrollEnabledisEditablefalseに設定します。TextViewの最小高さ制約を追加します

1行のテキストスクリーンショット

複数行のテキストのスクリーンショット

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)
        ])
    }
}
于 2021-05-12T08:54:56.560 に答える
1

@totiGの答えのSwift3バージョン

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)
    }
}
于 2016-11-17T15:35:25.610 に答える
1

私はこの問題を抱えていますが、私のラベルはにUITableViewCellあり、問題を解決する最も簡単な方法は、空を作成し、UIViewその中にラベルを上部と左側のみに制約を付けて設定することでした。 0までの行数

于 2019-09-10T23:43:24.440 に答える
1

@totiGの答えは正解で、私の問題を解決しました。しかし、このメソッドの実装中に問題が見つかりました。5s、SEなどの小さなデバイスでは、これは機能しません。私は設定label.sizeToFit()する必要がありますoverride func layoutSubViews()

override func layoutSubViews() {
    super.layoutSubViews()
    // Do other works if needed
    label.sizeToFit()
}
于 2019-11-18T14:37:11.290 に答える
1

textRect(forBounds:limitedToNumberOfLines:)を使用します

class TopAlignedLabel: UILabel {
      override func drawText(in rect: CGRect) {
        let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        super.drawText(in: textRect)
      }
}
于 2021-07-08T07:27:09.873 に答える
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];
}
于 2015-08-26T10:04:19.233 に答える
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)
于 2016-03-29T06:19:21.303 に答える
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)
于 2020-01-28T05:14:55.733 に答える
0

ビュー内にタグを埋め込むことで修正できました。それは完璧に機能しました!

修正方法:ラベルをビューに埋め込む

于 2021-09-28T23:13:37.723 に答える
0

layoutSubviewsで設定する必要があります。

override func layoutSubviews() {
   super.layoutSubviews()
   yourLabel.sizeToFit()
   //yourLabel.center.x = someView.center.x // optionally if exists
}
于 2022-01-27T13:22:10.557 に答える
-3

iOSアプリケーションのUILabelの左上の配置を設定するにはどうすればよいですか?ラベルセットコンテンツモードを「左上」に設定してください。ありがとうございます。
iOSアプリケーションのUILabelの左上の配置を設定するにはどうすればよいですか? ラベルセットコンテンツモード

于 2018-08-26T11:37:13.583 に答える