0
我試圖創建迅速,但有困難建立一個代表....繼承人是我迄今爲止...IOS斯威夫特:在自定義類使用委託方法
BarChart.swift條形圖類:
import Foundation
import UIKit
@objc protocol BarChartDelegate {
optional func barChart(colorForBarAtIndex index: Int) -> UIColor
}
class BarChart : BarChartDelegate {
let data : [NSDecimalNumber]
let container = UIView()
var barWidth : CGFloat = 100
var barSpacing : CGFloat = 10
var delegate : BarChartDelegate?
init(data: [NSDecimalNumber], frame: CGRect) {
self.data = data
self.container.frame = frame
drawGraph()
}
func drawGraph() {
var i = 0
for item in self.data {
var bar = UIView()
let xPos = CGFloat(i)*self.barWidth
bar.frame = CGRectMake(xPos, 0, self.barWidth, 100)
if let del = delegate? {
bar.frame
println(del.barChart!(colorForBarAtIndex: i))
bar.backgroundColor = del.barChart!(colorForBarAtIndex: i)
}
else {
println("nope!")
}
self.container.addSubview(bar)
i++
}
}
}
ViewController.swift
class ViewController: UIViewController, BarChartDelegate {
var colors = [
UIColor.greenColor(),
UIColor.blueColor(),
UIColor.redColor()
]
override func viewDidLoad() {
super.viewDidLoad()
var barChart = BarChart(data: [NSDecimalNumber(double: 100.00), NSDecimalNumber(double: 200.00), NSDecimalNumber(double: 300.00)], frame: CGRectMake(0, 0, 400.00, 100.00))
self.view.addSubview(barChart.container)
}
func barChart(colorForBarAtIndex index: Int) -> UIColor { // this is not running?
return self.colors[index]
}
}
在我ViewController.swift文件中的委託方法沒有運行,我只是得到"nope!"
打印到控制檯3倍。W這是代表的結果,可選的發現零時解包?
有什麼我在這裏失蹤?
任何幫助,將不勝感激!
謝謝, 戴夫
感謝您的快速回復sapi! 將委託參數添加到構造函數爲我工作 謝謝! – David