ios - 如何隐藏所有图像并仅显示我想要显示的选定图像?
问题描述
对于这个程序,我试图让课程的难度以星星的形式表示,它们都是它们自己独立的图像视图。我已经完成了项目的其余部分,但我完全不知道如何让一定数量的星星显示出来,其余的隐藏起来。
例如,如图所示,如果选择 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
}
}
解决方案
不是字符串数组,而是包含星数属性的结构数组
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
达到每门课程的课程级别和星级。
推荐阅读
- python - 错误:张量流:无法理解架构名称“.50_%image_size%”
- php - “一般错误:1366 不正确的整数值”即使我已将验证设置为可为空
- amazon-web-services - 在 Cognito 中结合 client_credentials 和自定义身份验证流程?
- java - 从 ArrayList 填充 Spinner
> - angular - 将元素传递给 Angular 中的函数
- ruby-on-rails - Rails 控制器方法没有被调用
- python-3.x - Python迭代器在for-in循环内修改其列表时出现意外行为
- javascript - 如何在 PHP 中调试“遇到的非数字值”?
- ios - 用键盘向上移动 UITextField - swift 4.2 的变化?
- javascript - javascript中的反引号语法函数调用