UIButton added to UITableViewCell will not display
After reading all the examples here and elsewhere I wrote the following code to add a button to a UITableViewCell, but I cannot get it to display in the cell. What am I doing wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithI开发者_开发技巧dentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)];
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell.contentView addSubview:cellButton];
[cellButton release];
return cell;
}
Thanks, John
There is no need to call release
on a button you have created via buttonWithType
; by calling release you are causing the retain count to drop, and at some point the button will be destroyed before you want it to.
You're doing two things wrong. First, as the above poster said, you're overreleasing the button, and the program may crash some point in the future. As a rule, static methods will return autoreleased objects, so you don't need to release it yourself (unless you retained it beforehand).
Also, since you're reusing the tablecell, the code above will add a UIButton to the cell multiple times, which is probably not your desired behavior. Add the UIButton when the table cell is initialized. Also, you may want to make sure the button rect is inside the table cell as a sanity check.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)];
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell addSubview:cellButton];
}
return cell;
}
精彩评论