根据bool

时间:2016-08-05 21:26:32

标签: swift loops

我有多个成就,用户可以在游戏中实现。当用户进入成就VC时,他应该在完成成就时看到图像。

我现在在viewDidLoad函数中使用此代码:

if unlockedAchievement1 == true
        {
            achievement1Text.textColor = UIColor.greenColor()
            achievement1Image.image = UIImage(named: "achievement1Unlocked")
        }
        if unlockedAchievement2 == true
        {
            achievement2Text.textColor = UIColor.greenColor()
            achievement2Image.image = UIImage(named: "achievement2Unlocked")
        }

这样可行,但需要花费大量时间来粘贴这个加班时间。我怎样才能缩短这个?我应该上课吗?我读了关于in循环,但我不太明白。欢迎任何帮助!

2 个答案:

答案 0 :(得分:0)

我觉得我以前见过这个。但无论如何......

//use array of bools. First declare as empty array.
//Use Core data to achieve saving the Booleans if you need to. 
let achievements:[Bool] = [] 
let achievementsImage:[UIImage] = []
let achievementsText:[UITextView] = []

func viewDidLoad() {
    //Say you have 5 achievements.
    for index in 0 ..< 5 {
        achievements.append(false)
        achievementsImage.append(UIImage(named: "achievementLocked"))
        achievementText.append(UITextView())
        //Then you can edit it, such as.
        achievementText[index].frame = CGRect(0, 0, 100, 100)
        achievementText[index].text = "AwesomeSauce"
        self.view.addSubview(achievementText[index])
        achievementText[index].textColor = UIColor.blackColor()
    }
}

//Call this function and it will run through your achievements and determine what needs to be changed
func someFunction() {
    for index in 0 ..< achievements.count {
        if(achievements[index]) {
            achievements[index] = true
            achievementsImage[index] = UIImage(named: String(format: "achievement%iUnlocked", index))
            achievementsText[index].textColor = UIColor.greenColor
        }
    }
}

答案 1 :(得分:0)

我建议您制作unlockedAchievement1unlockedAchievement2等对象元组,第一个值是原始Bool,第二个值是图像名称。你可以使用这段代码:

// First create your data array
var achievements = [(Bool, String)]()
// Then you can make your achievements.
// Initially, they're all unearned, so the Bool is false.
let achievement1 = (false, "achievement1UnlockedImageName")
achievements.append(achievement1)
let achievement2 = (false, "achievement2UnlockedImageName")
achievements.append(achievement2)

// Now that you have your finished data array, you can use a simple for-loop to iterate.
// Create a new array to hold the images you'll want to show.
var imagesToShow = [String]()
for achievement in achievements {
    if achievement.0 == true {
        imagesToShow.append(achievement.1)
    }
}