非常简单,我只想根据一天中的时间更改backgroundView的颜色,但由于某种原因它不起作用.任何帮助都会很棒. @IBOutlet weak var backgroundView: UIView!override func viewDidLoad() { super.viewDidLoad() let darkC
@IBOutlet weak var backgroundView: UIView! override func viewDidLoad() { super.viewDidLoad() let darkColor=UIColor(red: 51, green: 52, blue: 50, alpha: 1.0) let greyColor=UIColor(red: 238, green: 240, blue: 239, alpha: 1.0) let hour = NSCalendar.current.component(.hour, from: NSDate() as Date) switch hour { case 1..<6: self.backgroundView.backgroundColor = darkColor break case 7..<18: self.backgroundView.backgroundColor = greyColor break case 19..<24: self.backgroundView.backgroundColor = darkColor break default:self.backgroundView.backgroundColor = greyColor } }问题是以下几行分别忽略6,18,24:
1..<6 //1 - 5 7..<18 //7 - 17 19..<24 //19 - 23
根据您的时间,检查时间;如果它恰好落在6号,18号,24号,那么它可能就是你认为它不起作用的原因.
使用您的代码,我确认视图的backgroundColor确实发生了变化.
尝试将代码更改为以下内容:
switch hour { // hours 1 to 6 case 1...6: self.backgroundView.backgroundColor = darkColor break // hours 7 to 18 case 7...18: self.backgroundView.backgroundColor = greyColor break //hours 19 to 23 and 0 case 19...23, 0: self.backgroundView.backgroundColor = darkColor break default:self.backgroundView.backgroundColor = greyColor }
另一个问题如下:
let darkColor=UIColor(red: 51, green: 52, blue: 50, alpha: 1.0) let greyColor=UIColor(red: 238, green: 240, blue: 239, alpha: 1.0)
因为他们应该:
let darkColor = UIColor(red: 51/255, green: 52/255, blue: 50/255, alpha: 1.0) let greyColor = UIColor(red: 238/255, green: 240/255, blue: 239/255, alpha: 1.0)