为什么我的子类'变量不存在?

时间:2014-11-21 07:26:18

标签: ios swift

我创建了一个UILabel的子类UIScoreLabel,它更专业于我需要显示分数。这是代码:

class UIScoreLabel: UILabel
{
    var scoreBackingInt: Int!
    var score: Int {
        get
        {
            return scoreBackingInt
        }
        set(newScore)
        {
            scoreBackingInt = newScore
            self.text = NSString(format: "%0\(digits)d", newScore)
        }
    }
    let digits: Int!    // number of digits to display (for 0-padding)

    init(digits: Int)
    {
        super.init()
        self.digits = digits
        self.score = 0
    }
}

score应该是一个计算变量。无论如何,当我实例化UIScoreLabel时,一切都很好,但是当我尝试访问任何子类时#39;任何方式的属性(即score),编译器告诉我'UILabel' does not have a member named 'score'

以下是在我的ViewController中给出错误的行:

creditsLabel.score = self.score

是什么给出了?

2 个答案:

答案 0 :(得分:3)

您需要让编译器知道类类型。正如您在错误消息中看到的那样,编译器当前认为该类为UILable,因此您需要更新类类型(或者如果可以,则转换类类型。)

答案 1 :(得分:2)

UILabelUIView的子类,UIView的默认初始值设定项为init(frame: CGRect)。这是您在调用super时需要使用的初始化程序。

  super.init(frame: CGRectZero)
  self.digits = digits
  self.score = 0

此外UILabel采用NSCoding并拥有您需要实施的必需init。由于您没有使用故事板,您可以添加以下内容以消除编译器错误:

  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented") 
  }
相关问题