开发者

Place two UILabels side by side left and right without knowing string length of text in left label

In the photos tab of the iPhone fb app, for each table view cell they put the album title followed by the number of pictures in the album.

For example,

THE FIRST ALBUM (22)

THE LAST AND FINAL AL... (12开发者_如何学C)

I think there are two labels, one for the title and one for the number, because the number is actually a different UIColor. How do u create the effect where the number floats to the left depending on the size of the title?(Note: i can't use a uiwebview because this is in a uitableview)


sizeWithFont is your friend here. You use it as follows to get the results you want:

UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectZero]; //for album titles
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectZero]; //for number of pics

/*
 Set other label properties 
 such as background color, 
 font size, font color, etc
*/

NSString *string1 = [NSString stringWithFormat:@"This is a title"];
NSString *string2 = [NSString stringWithFormat:@"22"];

//Let's say both strings have a font size of 12.0f

CGSize string1Size = [string1 sizeWithFont:[UIFont systemFontOfSize:12.0f]];

label1.text = string1;
label2.text = string2;

label1.frame = CGRectMake(0/*or any origin x*/,0/*or any origin y*/,string1Size.width, string1Size.height];

label2.frame = CGRectMake(label1.frame.origin.x + label1.frame.size.width + 5/*or any other padding*/,label1.frame.origin.y, 40.0/*or some other fixed width*/,label1.frame.size.height);

Now just add them as subviews and you're done!


You can use the first label's sizeThatFits: method to retrieve the size of the label that would fit in the available space, and then position the second label based on the resulting width of the first.

Or you could do about the same thing using the various NSString UIKit additions to measure the length of the string.

Or you could make your own custom view and draw the text yourself in drawRect:, although that is not recommended when other simple solutions exist (custom drawRect:s make UIKit slow).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜