从类文件初始化委托

时间:2016-01-22 16:43:57

标签: ios swift function delegates

我正在使用swift构建应用程序。我试图传递信息并从自定义AnnotationClusterView的类文件中触发一个函数到ViewController。为此,我实现了一个委托。但我不知道在哪里以及如何初始化它。这是自定义的AnnotationClusterView类:

import Foundation
import MapKit

protocol MyDelegate {
    func thatGuy(guy: Int)
}

class FBAnnotationClusterView : MKAnnotationView {
    var delegate: MyDelegate!
    var countLabel:UILabel? = nil


    override init(annotation: MKAnnotation?, reuseIdentifier: String?){
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        let cluster:FBAnnotationCluster = annotation as! FBAnnotationCluster

        for annot in cluster.annotations {
            let fbannot: FBAnnotation = (annot as? FBAnnotation)!
            imageArray.append(fbannot.image)
        }
        setupButtons()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func setupButtons() {
        var xFactor = 1
        for butt in self.imageArray {
            let yFactor = CGFloat(xFactor * 40)
            let buttButt: UIButton = UIButton(frame: CGRectMake(yFactor, 80, 16, 16))
            buttButt.setImage(butt, forState: UIControlState.Normal)
            buttButt.tag = xFactor
            buttButt.addTarget(self, action: "thumbButt:", forControlEvents: UIControlEvents.TouchUpInside)
            addSubview(buttButt)
            xFactor++
        }
    }


    func thumbButt(sender: UIButton) {
        print("Button Pressed")
        self.delegate?.thatGuy(sender.tag)
    }

}

这是ViewController代码:

    import MapKit
    import UIKit

    class ViewController: UIViewController, MKMapViewDelegate, MyDelegate {
       override func viewDidLoad() {
          ...
       }

       func thatGuy(guy: Int) {
           print("thatGuy func reached!")
       }

1 个答案:

答案 0 :(得分:2)

您可以在viewDidLoad中执行此操作:

var annotationView = FBAnnotationClusterView(...
annotationView.delegate = self;

那应该做的。

但我认为你应该在

中创建注释
  viewForAnnotation

MapView协议的方法以及应该创建视图并委托就座的地方。