Search code examples
objective-cios6uilabelautolayout

How can i achieve Multiline UILabel with NSLineBreakByTruncatingMiddle and sizeToFit in autolayout?


I have a two line UILabel. I want its line break mode NSLineBreakByTruncatingMiddle. The problem i am getting is if text is small enough to fit in one line, its showing it in middle of label instead of at top. I am using iOS6 and autolayout so sizeToFit is not working for me. How can i achieve this? I want if text is small to fit one line it should be vertically top aligned. I have tried this, but its truncating and showing the text in one line only rather than two line.


Solution

  • You need to calculate the required size and update the frame of your label:

    CGSize s = [myLabelString sizeWithFont:...
                         constrainedToSize:CGSizeMake(..., MAXFLOAT)
                             lineBreakMode:NSLineBreakByTruncatingMiddle];
    

    With whatever font your label is using and its width.