Tuesday 16 July 2013

UILabel top aligned. Align text to top left. The text is displayed in the vertical center of the label? NSTextAlignment.


 UILabel if text in label is too short to fit in the number of lines used for that label, the text is displayed in the vertical center of the label.






To vertically align the text at the top of the UILabel

    _titleLabel.text = [self._myArray objectAtIndex:indexPath.row]; // get text array.


    [_titleLabel setNumberOfLines:0]; 
    // 


    [_titleLabel sizeToFit];




3 comments:

  1. It doesn't work with xcode 6 (for iPad app). Just do nothing.

    ReplyDelete
  2. Hmm... In Xamarin It works fine:
    public class NewsTableViewHeader : UIImageView
    {
    private UILabel headerLabel { get; set; }

    public NewsTableViewHeader(string text, UIImage image, CGRect frame) : base(image)
    {
    headerLabel = new UILabel(new CGRect(20, 10, frame.Width - 20, frame.Height - 10));
    headerLabel.TextColor = UIColor.White;
    headerLabel.BackgroundColor = UIColor.Clear;
    headerLabel.Font = UIFont.SystemFontOfSize(24);
    headerLabel.Text = text;
    headerLabel.TextAlignment = UITextAlignment.Left;
    headerLabel.LineBreakMode = UILineBreakMode.WordWrap;

    #region Fix align label text to top
    headerLabel.Lines = 0;
    headerLabel.SizeToFit();
    #endregion

    this.AddSubview(headerLabel);

    this.Frame = frame;

    this.AddConstraint(NSLayoutConstraint.Create(
    this,
    NSLayoutAttribute.Height,
    NSLayoutRelation.Equal,
    this,
    NSLayoutAttribute.Width,
    9.0f / 16.0f,
    0));
    }
    }

    ReplyDelete