在循环中动态引用propertyName + 1

时间:2012-06-03 08:13:26

标签: objective-c ios xcode optimization

尝试清理一些代码并遇到问题。我有一个1-5排名出现在uitableviewcell中。单元格有5个图像视图,指向星形图像。有一个starYellow.png和starGrey.png。如果排名为3/5,则单元格应将star1,star2,star3设置为starYellow.png,将star4,star5设置为starGrey.png。

我在引用属性星%i时遇到问题,其中i是循环1-5的迭代。我无法解决如何做某事[cell setValue:starYellow forKey:[NSString stringWithFormat:@“star%i.image”,i]];

以下是我想要优化的代码..

if (book.ratingOnline) {
[cell.ratingView.layer setOpacity:1.0f];
    for (int i = 1; i <= 5; i++) {            
        if (i == 1) {
            if (book.ratingOnline >= i) { [cell.star1 setImage:[UIImage imageNamed:@"starYellow.png"]]; }
            else { [cell.star1 setImage:[UIImage imageNamed:@"starGrey.png"]]; }
        }
        else if (i == 2) {
            if (book.ratingOnline >= i) { [cell.star2 setImage:[UIImage imageNamed:@"starYellow.png"]]; }
            else { [cell.star2 setImage:[UIImage imageNamed:@"starGrey.png"]]; }
        }
        else if (i == 3) {
            if (book.ratingOnline >= i) { [cell.star3 setImage:[UIImage imageNamed:@"starYellow.png"]]; }
            else { [cell.star3 setImage:[UIImage imageNamed:@"starGrey.png"]]; }
        }
        else if (i == 4) {
            if (book.ratingOnline >= i) { [cell.star4 setImage:[UIImage imageNamed:@"starYellow.png"]]; }
            else { [cell.star4 setImage:[UIImage imageNamed:@"starGrey.png"]]; }
        }
        else if (i == 5) {
            if (book.ratingOnline >= i) { [cell.star5 setImage:[UIImage imageNamed:@"starYellow.png"]]; }
            else { [cell.star5 setImage:[UIImage imageNamed:@"starGrey.png"]]; }
        }
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

在NSArray中添加所有星星,

在Cell.h中

NSArray *stars;

现在引用你可以做的任何开始

for (int i = 1; i <= 5; i++) {            
     UIImageView *star = [cell.stars objectAtIndex:i];
     //set the image to the star
}