首页 > 解决方案 > 如何隐藏所有图像并仅显示我想要显示的选定图像?

问题描述

对于这个程序,我试图让课程的难度以星星的形式表示,它们都是它们自己独立的图像视图。我已经完成了项目的其余部分,但我完全不知道如何让一定数量的星星显示出来,其余的隐藏起来。

例如,如图所示,如果选择 CSC 185,则应显示 2 颗星。我可以使用什么功能来做到这一点?

我已经尝试为每个不同的分段控制选项制作 if 语句来硬编码预期数量的星星,但我认为语法是错误的。我只学过 Java 类,所以我试图做出的陈述没有正确传递是 Swift。

我已经设置的界面示例。

这是我目前必须为课堂笔记显示正确的图像视图和课堂的正确标签的代码:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var classTypeSeg: UISegmentedControl!
    @IBOutlet weak var courseLabel: UILabel!
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var courseNotesImageView: UIImageView!
    @IBOutlet weak var firstStar: UIImageView!
    @IBOutlet weak var secondStar: UIImageView!
    @IBOutlet weak var thirdStar: UIImageView!
    @IBOutlet weak var fouthStar: UIImageView!
    @IBOutlet weak var fifthStar: UIImageView!
    var curCourse = "CSC 185"
    
    //This will list all of the different courses
    let courses: [String] = [
        "CSC 195",
        "CSC 190",
        "CSC 191",
        "CSC 308",
        "CSC 310",
        "CSC 313",
        "CSC 340",
    ]
    
    //This will make the picture for the notes represent the correct class
    @IBAction func classChoiceIsMade(_ sender: UISegmentedControl) {
        courseNotesImageView.image = UIImage(named: "\(curCourse).jpg")
    }
    
    //This will change the label to represent the correct class
    @IBAction func labelChoiceIsMade(_ sender: UISegmentedControl) {
        curCourse = sender.titleForSegment(at: sender.selectedSegmentIndex)!
        courseLabel.text = (curCourse)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        classTypeSeg.removeAllSegments()
        for i in 0..<courses.count {
            classTypeSeg.insertSegment(withTitle: courses[i], at: i, animated: false)
        }
        classTypeSeg.selectedSegmentIndex = 0
    }
}

标签: iosswift

解决方案


不是字符串数组,而是包含星数属性的结构数组

struct CSClass {
    let level: String
    let numStars: Int
}


let courses: [CSClass] = [
   CSClass(level: "CSC 190", numStars: 1),
   CSClass(level: "CSC 195", numStars: 2),
   //And so on for all the different classes
   ]

然后使用数组中的索引而不是段标题来跟踪所选类,然后使用

courses[selectedCourse].level

courses[selectedCourse].numStars

达到每门课程的课程级别和星级。


推荐阅读