我有9个按钮,其图像由用户动态设置。每个按钮的当前图像都保存在用户文档文件夹中。在viewDidLoad
id中,想要将每个图像重新设置为UIButton。
我可以很容易地做到这一点:
NSString *filePath = [self documentsPathForFileName: @"boss1.png"];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[boss1Button setImage:savedBoss forState:UIControlStateNormal];
...... 8 more times....
当然我喜欢用循环来做。只是,我不确定在客观C中会是什么样子。在jQuery中我可以做类似的事情:
$('.bosses').each(function( index ) {
var imageUrl='../images/boss'+(index+1)
$('#'+this.id).css('background-image', 'url(' + imageUrl + ')')
});
如何创建类似的objective-C
循环,同样会增加boss图像名称和按钮名称?
此外,还有更好的方法可以完全做到这一点吗?
我觉得可能有一个NSArray
的图片网址和一个UIButton
名称的NSArray,并使用循环将它们组合在一起可能会更好......但我又不知道是什么语法在这里看起来就像那样。
答案 0 :(得分:2)
尝试这样并拥有1到8的按钮标记
for (id subview in self.view.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)subview;
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFromate@"boss%d.png", button.tag]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[button setImage:savedBoss forState:UIControlStateNormal];
}
}
这样做。
答案 1 :(得分:1)
它会像:
//Add all the buttons in an array for easy loop
NSArray *array = @[btn1,btn2,btn3,btn4... etc];
NSString *name = @"BOSS";
int x = 1;
for(UIButton *btn in array){ // loop through all the buttons
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFormat:@"%@%d.png",name,x]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[btn setImage:savedBoss forState:UIControlStateNormal];
x++;
}