【发布时间】:2010-07-12 16:00:57
【问题描述】:
我创建了一个UIButtons 数组。我需要在不同时间以编程方式更改这些按钮上的图像。暂时,为了让它工作,我想在按下按钮时更改图像,但这不是真正发生的时候。
所以,我创建了一个按钮数组,并将它们排列在屏幕上的网格上:
for (UInt16 index=0; index < (mNumColumns * mNumRows); index++)
{
<....Snipped code for setting the x,y,width,height vars...>
UIButton *thisCell = [UIButton buttonWithType:UIButtonTypeCustom];
thisCell.tag = index;
thisCell.frame = CGRectMake(currentX, currentY, cellWidth, cellHeight);
[thisCell addTarget:self action:@selector(buttonPushed:)
forControlEvents:UIControlEventTouchUpInside];
[thisCell setImage:[UIImage imageNamed:@"cellBackground.png"]
forState:UIControlStateNormal];
[[self view] addSubview:thisCell];
}
---然后是按钮处理程序--
-(void)buttonPushed:(UIView*)clickedButton
{
NSLog(@"Click %d", clickedButton.tag);
[clickedButton setImage:[UIImage imageNamed:@"cellEmpty.png"]
forState:UIControlStateNormal];
[clickedButton setNeedsDisplay];
}
1) 按钮的初始网格正确显示。
2) 如果我将初始网格的 PNG 文件名更改为 cellEmpty.png,它适用于新图像,所以我知道图像可以显示。
3) 我在调试器中看到“单击 n”,因此正确的按钮正在调用 buttonPushed
但是,您可以猜到,图像没有得到更新。我认为此时我不想处理按钮状态....因为图像更改实际上与现实生活中按钮的按下状态无关(更改将是通过网络下载新图像的结果)。
【问题讨论】:
-
在您的 buttonPressed: 方法中,您已将 clickedButton 作为 UIView,因此 setImage: forState: 什么也不做。尝试将其类型转换为按钮,看看会发生什么
-
你的意思是这样做?
-(void)buttonPushed:(UIButton*)clickedButton
没有帮助。尽管我认为它不应该有所作为,因为无论类型转换如何,传递的对象仍然是 UIButton,对吗?我是 Objective C 的新手,但我认为您可以将事物作为超类传递并仍然获得派生消息处理?