views:

34

answers:

1

I have a list of items I'd like to show in a UITableViewCell. Right now, I'm simply using a cell.textLabel with commas separating each value, but I'd like to do something a little more dynamic.

How would I achieve something like this? alt text

Would it be an array of UILabels with borders and radius on those borders?

Thanks for your ideas.

+1  A: 

Here's a possible quick and easy way to do this. It's based on the code that you can get here.

Note that you have to add the QuartzCore framework to your project and include in the file where you write this code!

Every UIView is backed by a CALayer. You can get at the UIView's CALayer with the .layer property. Since a UILabel is a UIView, you can get its backing layer this way. Once you have the backing layer, you can set its backgroundColor, cornerRadius, borderColor, and borderWidth properties. That should let you create the rounded effect.

To get the centered effect, try setting the UILabel's textAlignment to UITextAlignmentCenter. Then, you could try setting the UILabel's frame based on sizeThatFits, or maybe based on calling sizeWithFont on the string you're putting into the label.

Here's some quick, totally untested code to get you started.

Assume that somewhere you've initialized a UIFont as follows (put in whatever size you want for the font).

labelFont = [UIFont systemFontOfSize:14];

Then, for each label, set it up as follows.I'm assuming you've pulled the text out of an array and put into a variable called "text". X_PADDING and Y_PADDING are how much spacing you want around the label's text. xLoc and yLoc are variables you're using to keep track of the x and y position you want to put the labels at. You'll probably increase xLoc based on textSize + X_PADDING + LABEL_SPACING or something (where you define LABEL_SPACING):

 CGSize textSize = [text sizeWithFont:labelFont];
 CGRect frame = CGRectMake( xLoc, yLoc,
                            textSize.width + X_PADDING,
                            textSize.height + Y_PADDING);
 UILabel *label = [[UILabel alloc] initWithFrame:frame];
 label.text = text;
 label.textAlignment = UITextAlignmentCenter;

 CALayer *layer = label.layer;
 layer.masksToBounds = YES;
 layer.cornerRadius = 7.0; // or whatever works for you
 layer.borderWidth = 1.0;
 layer.borderColor = [[UIColor redColor].CGColor;
 layer.backgroundColor = [UIColor blueColor].CGColor;

 // Add the layer into its superview
 [yourSuperview addSubview:label];

I hope this helps get you started.

Jacques