Top aligned UILabel, make text stick to top of label view

Is there a way to "top align" a UILabel, that is make text stick to top of label view? As opposed to center aligned vertically, or float in the center of the view, as is the default?

Here is an image of three labels, aligned left, right and center, and a UITextView that is aligned center and top. The text of the textView sticks to the top regardless of the vertical size of the view. Can I do the same thing with a label?

在这里输入图像描述


There is no way to set the vertical alignment of a UILabel by default in iOS. Instead, you will want to use one of the sizeWithFont methods provided by NSString . Which one you use depends on whether you want a multi-line or single-line label. sizeWithFont:forWidth:lineBreakMode: can be used for single-line labels, while sizeWithFont:constrainedToSize:lineBreakMode: can be used for multi-line labels. You can easily load the font parameter with the font property of the label in question. You can look here for some more details on using these functions.

These methods will return a CGSize struct with the minimum size for your label based on the text in the NSString . Once you have the correct size for the label, you can easily place it at the top of your superview and it will appear to be top-aligned.


There's a workaround for it:

  • Set a height & width constraint to your UILabel with a constant <= to the maximum height|width you want.
  • Set number of lines to zero.
  • Set the height in storyboard to fit only one line.
  • In your code after setting the text of UILabel call sizeToFit .
  • This would make your UILabel to resize within the bounds of the maximum width & height you want and text will always be top aligned.


    I used the answer linked above from nevan king in a comment to my question: Vertically align text to top within a UILabel

    The code I used is here:

    - (void)setUILabelTextWithVerticalAlignTop:(NSString *)theText {
        CGSize labelSize = CGSizeMake(250, 300);
        CGSize theStringSize = [theText sizeWithFont:targetLabel.font constrainedToSize:labelSize lineBreakMode:targetLabel.lineBreakMode];
        targetLabel.frame = CGRectMake(targetLabel.frame.origin.x, targetLabel.frame.origin.y, theStringSize.width, theStringSize.height);
        targetLabel.text = theText;
    }
    
    //linked to a button that sets the text from a UITextView to the label.
    - (IBAction)setText:(id)sender {
    
        [sourceText resignFirstResponder];
        [self setUILabelTextWithVerticalAlignTop:sourceText.text];
        [targetLabel setNumberOfLines:0];
        [targetLabel sizeToFit];
    
    }
    

    Here is the project:

    owolf.net/uploads/StackOverflow/verticalAlignUILabel.zip

    链接地址: http://www.djcxy.com/p/4842.html

    上一篇: 在自动布局中使用UILabel

    下一篇: 顶部对齐的UILabel,使文本粘在标签视图的顶部