原本我以為要讓一個多行(numberOfLines > 1)UILabel元件的文字在垂置方向置頂只要寫個類似: (原本預設是置中align middle。可是這樣有時候不是你想要的排列方式,因為中間可能會多出很多空白…)
label.textAlignment = UITextAlignmentLeft;
這樣的code,一行就可搞定…。沒想到Apple居然連這樣基本的方法都沒有提供,搞的大家為了讓Label置頂還要寫一堆code來達成 ~”~…. (又是Objective-C不好用的一個證明)
上網孤了半天,整理了一下網友的寫法,寫成一個Util function,之後就不必再為這個鳥問題煩惱啦~ 如果覺得好用的話,歡迎copy拿去用沒關係…
// adjust the height of a multi-line label to make it align vertical with top + (void) alignLabelWithTop:(UILabel *)label { CGSize maxSize = CGSizeMake(label.frame.size.width, 999); label.adjustsFontSizeToFitWidth = NO; // get actual height CGSize actualSize = [label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode]; CGRect rect = label.frame; rect.size.height = actualSize.height; label.frame = rect; }
使用方法(假定lblHello是由Interface Builder做出來的):
lblHello.text = @"Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!"; lblHello.numberOfLines = 5; [Utils alignLabelWithTop:lblHello];
code參考:
http://stackoverflow.com/questions/1054558/uilabel-vertical-alignment