我有一个带注释的地图视图,每个注释都有一个日期,月份和时间的相应日期。
我正在把这一天推到新的视图控制器,然后使用switch
查看它所属的月份的哪一天,然后显示相应的日历图标。我不能把func
放在viewDidAppear以外的任何地方,导致短暂的滞后和两次,阻止我使用
for view in self.view.subviews {
view.removeFromSuperview()
}
所以有两个问题:
这是负责显示图像的代码:
override func viewDidAppear(animated: Bool) {
dayCalendar()
}
func dayCalendar() {
switch day {
case 1:
let calendarDay = "Calendar 1-50.png"
let calendarDayImage = UIImage(named: calendarDay)
let calendarDayImageView = UIImageView(image: calendarDayImage!)
calendarDayImageView.frame = CGRect(x: 25 , y: 350, width: 50, height: 50)
self.view.addSubview(calendarDayImageView)
case 8:
let calendarDay = "Calendar 8-50.png"
let calendarDayImage = UIImage(named: calendarDay)
let calendarDayImageView = UIImageView(image: calendarDayImage!)
calendarDayImageView.frame = CGRect(x: 25 , y: 350, width: 50, height: 50)
self.view.addSubview(calendarDayImageView)
case 11:
let calendarDay = "Calendar 11-50.png"
let calendarDayImage = UIImage(named: calendarDay)
let calendarDayImageView = UIImageView(image: calendarDayImage!)
calendarDayImageView.frame = CGRect(x: 25 , y: 350, width: 50, height: 50)
self.view.addSubview(calendarDayImageView)
case 12:
blahh blahh blahh all the way down
case 31:
let calendarDay = "Calendar 30-50.png"
let calendarDayImage = UIImage(named: calendarDay)
let calendarDayImageView = UIImageView(image: calendarDayImage!)
calendarDayImageView.frame = CGRect(x: 25 , y: 350, width: 50, height: 50)
self.view.addSubview(calendarDayImageView)
default:
println("Default")
break
}
}
答案 0 :(得分:2)
首先:你为什么要切换?据我所知,代码可以简化为
func dayCalendar() {
if day < 1 || day > 31 {
return
}
let calendarDay = "Calendar \(day)-50.png"
let calendarDayImage = UIImage(named: calendarDay)
let calendarDayImageView = UIImageView(image: calendarDayImage!)
calendarDayImageView.frame = CGRect(x: 25 , y: 350, width: 50, height: 50)
self.view.addSubview(calendarDayImageView)
}
您可能希望将呼叫转移到viewWillAppear
。
要修复细节闭包的重叠,您有两个选择:
calendarDayImageView
。或(更好)
您可以通过以下方式实现后者:
// add this variable to your class
lazy var calendarDayImageView: UIImageView = {
[unowned self] in
let imageV = UIImageView(frame: CGRect(x: 25 , y: 350, width: 50, height: 50))
self.view.addSubview(imageV)
return imageV
}()
// change the dayCalender to make use of the newly added variable
func dayCalendar() {
if day < 1 || day > 31 {
return
}
let calendarDay = "Calendar \(day)-50.png"
let calendarDayImage = UIImage(named: calendarDay)
calendarDayImageView.image = calendarDayImage
}
或者你可以在viewDidLoad中移动视图的初始化,并再次dayCalender
设置实际图像 - 但我喜欢懒惰变量;)