IOS Swift:在自定义类中使用委托方法

时间:2015-01-04 23:13:03

标签: ios swift

我正在尝试在swift中创建一个条形图类,但是很难设置代理....这是我到目前为止所拥有的......

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次...这是委托可选的在打开时找到nil的结果?

我在这里缺少什么?

任何帮助将不胜感激!

谢谢, 戴夫

1 个答案:

答案 0 :(得分:1)

首先,BarChart也很少有BarChartDelegate。你没有把事情委托给自己!

其次,据我所知,实际上并没有将ViewController设置为BarChart的代表。简单地采用BarChartDelegate协议是不够的;你需要明确地设置它。

因此,例如,您可能希望在创建BarChart

后执行此操作
var barChart = ...
barChart.delegate = self

或者,如果委托对您的图表至关重要,您可能希望更改构造函数以接受委托作为参数。

相关问题