我有许多不同的Coregraphics函数,它们描绘了一个表盘的不同元素。我希望放在一起的逻辑确定基于从当前小时拉出的变量显示时钟面的哪个方面。所有绘制方法都列在单独的swift类/文件中。而不是创建if语句塔,我如何简化此过程以将变量注入到被称为的方法中?在这里你可以看到drawCanvas04()与下午4:00(或16小时)相关联。
class ViewController: UIViewController {
func updateTime() {
var date:NSDate = NSDate()
var calendar:NSCalendar = NSCalendar.currentCalendar()
var components:NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond, fromDate: date)
var hour = components.hour
var minute = components.minute
var seconds = components.second
var time = "\(hour) : \(minute) : \(seconds)"
println("\(time)")
if hour == 16 || hour == 04 {
ClockStyleKit.drawCanvas04()
} else {
if hour == 17 || hour == 05 {
ClockStyleKit.drawCanvas05()
} else {
if hour == 18 || hour == 06 {
ClockStyleKit.drawCanvas06()
} else {
if hour == 19 || hour == 07 {
ClockStyleKit.drawCanvas07()
} else {
if hour == 20 || hour == 08 {
ClockStyleKit.drawCanvas08()
} else {
if hour == 21 || hour == 09 {
ClockStyleKit.drawCanvas09()
} else {
if hour == 22 || hour == 10 {
ClockStyleKit.drawCanvas10()
}
if hour == 23 || hour == 11 {
ClockStyleKit.drawCanvas11()
}
if hour == 24 || hour = 12 {
ClockStyleKit.drawCanvas12()
}
}
以下是调用样式包绘制方法的示例:
public class func drawCanvas07() {
//// Color Declarations
let color0 = UIColor(red: 0.894, green: 0.000, blue: 0.476, alpha: 1.000)
//// HOUR7 Drawing
var hOUR7Path = UIBezierPath(ovalInRect: CGRectMake(65.5, 155.99, 24, 24))
color0.setFill()
hOUR7Path.fill()
}
答案 0 :(得分:0)
使用参数。同样减少类方法,使用实例方法,如self.drawCanvas()
。
像这样:
func drawCanvas(canvas:Int) {
switch canvas {
case 0:
// do something here for 0 o clock
case 1:
// 1 o clock
// etc,
default:
// in case somehow you run out of bounds
}
}
并使用drawCanvas(10)
调用它。