I've got a custom class that inherits from UITableViewCell. I know how to dy开发者_如何学Cnamically add items to the custom cell by using layoutSubviews, however I've got a rather complex cell that I'd like to design from the Interface Builder and a XIB file.
Is there a way to do this? If so, how? Keep in mind, I'm very new at XCode so the more detail you provide the better. :)
Thanks in advance for the help.
In your UITableViewController subclass, add an IBOutlet for your custom cell class:
@property(nonatomic,retain)IBOutlet UITableViewCell *customCell;
Then, in your custom cell xib, set File's Owner to your UITableViewController subclass, and assign the outermost view to the IBOutlet on File's Owner. For each subview that you want to access programmatically, assign a unique value to its tag
property. Let's say your custom cell has 3 labels, which you've tagged 1, 2, and 3.
Finally, in your cellForRowAtIndexPath
method, load the nib into the outlet using the loadNibNamed
method. See the API docs for an explanation of how this works.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// assuming nib is MyCustomCell.xib
[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil];
// assign IBOutlet to cell
cell = customCell;
// clear IBOutlet
self.customCell = nil;
}
Now you can access the tagged views in your custom cell using the viewWithTag
method on your cell:
UILabel *label1 = (UILabel *)[cell viewWithTag:1];
label1.text = @"foo";
UILabel *label2 = (UILabel *)[cell viewWithTag:2];
label2.text = @"bar";
UILabel *label3 = (UILabel *)[cell viewWithTag:3];
label3.text = @"baz";
精彩评论