我看了很多资源,没有一个对我有用。我试图根据星期几来改变图像。我在游乐场测试了日历方法,它会返回正确的预期数字。但是,我对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
}
}
}
答案 0 :(得分:0)
您可以让您的功能更短更简单:
//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()
}
答案 1 :(得分:0)
我认为您的问题可能在此代码中:
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")
您可能需要说明图片的全名。例如,而不是:
var monday = UIImage(named: "monday")
您的代码可能必须是:
1) var monday = UIImage(named: "monday.png")
2) var monday = UIImage(named: "monday.jpg")
或任何其他图像类型。为所有图像执行此操作。
希望这可以帮助您解决问题。