这取决于您如何将子视图添加到您的 UITableViewCell 中:
-(UITableViewCell)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellID = @"cellID";
UITableViewCell *cell = [tableView dequeReusableCellForID:cellID];
if(cell == nil)
{
...
myButton = [[UIButton alloc] initWithFrame....];
[myButton addTarget:self selector:@selector(downloadImage:) forControlEvent:UIControlEventTouchUpInside];
// -------------------------------------------------------
// This is the important part here.
// Usually, we add "myButton" to the cell's contentView
// You will need to match this subview hierarchy
// in your "downloadImage:" method later
// -------------------------------------------------------
[cell.contentView addSubview:myButton];
}
return cell;
}
-(void)downloadImage:(id)sender
{
// -------------------------------------------------------
// Here, "sender" is your original "myButton" being tapped
//
// Then "[sender superview]" would be the parent view of your
// "myButton" subview, in this case the "contentView" of
// your UITableViewCell above.
//
// Finally, "[[sender superview] superview]" would be the
// parent view of the "contentView", i.e. your "cell"
// -------------------------------------------------------
UIButton *button = (UIButton *)sender;
// button now references your "myButton" instance variable in the .h file
[button setBackgroundImage:[UIImage imagenamed:@"filename.png"] forControlState:UIControlStateNormal];
}
希望有帮助。
至于为什么你的应用程序在你这样做时崩溃:
view = (UIButton*)subviews;
那是因为“子视图”是所有子视图的 NSArray。您告诉 iOS 将 NSArray * 类型转换为 UIButton *,但它不知道该怎么做。所以你最终导致应用程序崩溃。
在你的 for 循环中,你可能想要做这样的事情(尽管如果你使用我上面的“downloadImage”方法你不应该这样做):
for (view in subviews)
{
if([view isKindOfClass:[UIButton class]])
{
// ------------------------------------------------
// When you go for(view in subviews), you're saying
// view = [subviews objectAtIndex:i]
//
// Hence view = (UIButton *)subviews become
// redundant, and not appropriate.
// ------------------------------------------------
//view = (UIButton*)subviews; // <--- comment out/delete this line here
[view setBackgroundImage:[UIImage imageNamed:@"yellow"] forState:UIControlStateNormal];
}
}