gpt4 book ai didi

ios - 为什么 UIImage 不会改变?

转载 作者:行者123 更新时间:2023-11-28 09:12:15 25 4
gpt4 key购买 nike

我查看了很多资源,但没有一个对我有用。我正在尝试根据星期几更改图像。我在 Playground 上测试了日历方法,它会返回正确的预期数字。但是,我对 Swift 和编程以及一般知识还很陌生,对于为什么 imageChange 方法不会改变一无所知。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var schedule: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


var monday = UIImage(named: "monday")
var tuesday = UIImage(named: "tuesday")
var wednesday = UIImage(named: "wednesday")
var thursday = UIImage(named: "thurday")
var friday = UIImage(named: "friday")
var other = UIImage(named:"other")




func calendar()->Int{
let todayDate = NSDate()
let myCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)

let myComponents = myCalendar?.components(.WeekdayCalendarUnit, fromDate: todayDate)
let weekDay = myComponents?.weekday
return weekDay!
}
func imageChange() {
if calendar() == 2 {
schedule.image = monday
}

else if calendar() == 3 {
schedule.image = tuesday
}

else if calendar() == 4 {
schedule.image = wednesday
}

else if calendar() == 5 {
schedule.image = thursday
}

else if calendar() == 6 {
schedule.image = friday
}

else if calendar() == 7 {
schedule.image = other
}

else if calendar() == 1 {
schedule.image = other
}

else {
schedule.image = other
}
}
}

最佳答案

你可以让你的函数更短更简单:

//Add all your images to an array(other two times for saturday and sunday)
//0 = saturday, 1 = sunday, 2 = monday etc
var imageArray = [other, other, monday, tuesday, wednesday, thursday, friday]

func imageChange() {
//Call the function only one time. No need to call it each time you test
var calendarDay = calendar()

//You want to know which image you need from your array. -1 because an array starts at 0
var imageIndex = calendarDay - 1

schedule.image = imageArray[imageIndex]

}

要调用您的函数,您必须在函数内部进行。您不能仅从类体内运行函数。因此,例如在您的 viewDidLoad 方法中:

override func viewDidLoad() {
super.viewDidLoad()
imageChange()
}

关于ios - 为什么 UIImage 不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28918755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com