我正在研究一个脚本,该脚本循环遍历按数字顺序设置并由标签选择的LED UIImageView数组。根据步骤(aka数字)的不同,LED图像上的指示灯将显示为开或关。此方法的主要目标是采取当前步骤并显示“LED亮”图像,同时将其减去1,然后显示上一步的“LED灭”图像。因此,一次只能点亮一个LED。
不幸的是,我只能使“LED亮”图像正确显示。该序列中的所有LED均点亮,但它们从未熄灭。我的第一个猜测是我没有以正确的方式减去NSInterger。但是,当我检查日志时,一切都应该在原处。如果当前步骤是2,则上一步是1。不知道为什么它不起作用。谢谢!
sequencerLocation和previousLocation都设置为属性。
- (void)clockLoop:(UInt8)seqClockPulse
{
//cast to an int to use in loop
NSInteger stepCount = sequencerSteps;
//increment sequencer on pulse in
sequencerLocation++;
if(sequencerLocation > stepCount)
{
sequencerLocation = 1;
}
//setup previous step location
previousLocation = (sequencerLocation - 1);
if (previousLocation == 0)
{
previousLocation = stepCount;
}
//change led color in led array
for (UIImageView *led in sequencerLEDArray)
{
if(led.tag == sequencerLocation)
{
UIImageView *previousLed = (UIImageView *)[led viewWithTag:previousLocation];
[previousLed setImage:[UIImage imageNamed:@"images/seq_LED_off.png"]];
NSLog(@"Previous: %d", previousLocation);
UIImageView *currentLed = (UIImageView *)[led viewWithTag:sequencerLocation];
[currentLed setImage:[UIImage imageNamed:@"images/seq_LED_on.png"]];
NSLog(@"Current: %d", sequencerLocation);
}
}
}
最佳答案
//change led color in led array
for (UIImageView *led in sequencerLEDArray)
{
if(led.tag == sequencerLocation)
{
// I THINK the problem is here
// UIImageView *previousLed = (UIImageView *)[led viewWithTag:previousLocation];
// TRY THIS instead
UIImageView *previousLed = [led.superview viewWithTag:previousLocation];
[previousLed setImage:[UIImage imageNamed:@"images/seq_LED_off.png"]];
NSLog(@"Previous: %d", previousLocation);
// HERE you don't need to search for the tag you already tested for it in your if statement
UIImageView *currentLed = (UIImageView *)[led viewWithTag:sequencerLocation];
[currentLed setImage:[UIImage imageNamed:@"images/seq_LED_on.png"]];
NSLog(@"Current: %d", sequencerLocation);
}
}
viewWithTag:
Discussion
此方法在当前视图及其所有子视图中搜索指定的视图。
因此,当您通过自身的标签搜索
led
时,它会自动返回,但是当您搜索其兄弟时却找不到它,这就是为什么我建议将led.superview
作为搜索标签的地方的原因,父级应该能够找另一个孩子关于objective-c - 根据标签设置UIImage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8737097/