自定义数据源方法不是在swift 2.0中调用

时间:2016-03-18 11:37:53

标签: swift2 xcode7

这是我的BorderView,我尝试做的任务是将自定义对象(Border)连接到主故事板。

import UIKit
protocol BorderViewDataSource: class{
func colorForBorderView(sender:BorderView) -> String? }
class BorderView: UIView {

@IBOutlet weak var topLeftImage: UIImageView!
@IBOutlet weak var topRightImage: UIImageView!
@IBOutlet weak var bottomLeftImage: UIImageView!
@IBOutlet weak var bottomRightImage: UIImageView!

var view: UIView!

weak var dataSource:BorderViewDataSource?


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

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

    xtraSetup()
}


func xtraSetup() {

    view = loadViewFromNib()

    // use bounds not frame or it'll be offset
    view.frame = bounds

    // Make the view stretch with containing view
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
    // Adding custom subview on top of our view (over any custom drawing > see note below)      
    addSubview(view)
    let borderColor = dataSource?.colorForBorderView(self) ?? "red"
    applyColor(borderColor)

}

// this is an actual load from nib module
func loadViewFromNib() -> UIView {

    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "BorderView", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

    return view
}

func applyColor(borderColor:String){
    var imageName = "border-topleft-\(borderColor)"
    topLeftImage.image = UIImage(named: imageName)
    imageName = "border-topright-\(borderColor)"

    print("Border color is \(borderColor), and Last image name is \(imageName)")


}
}

因此,当我打开应用程序时,它将显示不同颜色的图像,具体取决于在ViewContorller.swift中设置颜色的值,这是我的viewcontroller。快速代码

class ViewController: UIViewController, BorderViewDataSource {

var borderType = 2
@IBOutlet weak var borderView: BorderView!{
    didSet{
        borderView.dataSource = self
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func colorForBorderView(sender: BorderView) -> String? {

    var borderColor = "blue"
    switch borderType {
        case 1: borderColor = "blue"
        case 2: borderColor = "purple"
        case 3: borderColor = "red"
        default: break
    }
    print("Border Type is \(borderType), and border color is \(borderColor)")
    return borderColor
}

}

colorForBorderView 方法在我运行应用时没有调用

2 个答案:

答案 0 :(得分:0)

初始化视图时,该视图的dataSource属性为nil。并且您只在视图初始化期间调用该方法。您可以在视图控制器中viewDidLoad()之后应用颜色

答案 1 :(得分:0)

来自文档:

  

为存储的属性分配默认值或设置其值时   初始化程序中的初始值,设置该属性的值   直接,不要求任何财产观察员。

这就是没有设置数据源的原因。将行borderView.dataSource = self放入viewDidLoad()