访问BFPaperButton子类中定义的属性时崩溃

时间:2014-08-15 01:19:38

标签: ios uibutton swift init uicontrol

我正在研究在Swift中创建一个自定义按钮。

当我将UIButton类子类化时,它可以正常工作。

但是当我用BFPaperButton(https://github.com/bfeher/BFPaperButton)替换超类时它崩溃了

我已修复了init方法名转换错误:

#define initFlat initWithFlat
#define initFlatWithFrame initWithFlatWithFrame
#define initRaised initWithRaised
#define initRaisedWithFrame initWithRaisedWithFrame

然后我在访问新定义的属性时获得了EXC_BAD_ACCESS:

(An UserCountButton Instance).countLabel.text = ...

这是我的实施:

import UIKit

class UserButton: BFPaperButton {
    let footerLabel = UILabel()
    override init() {
        super.init(flatWithFrame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width / 3, height: 100))
        addSubview(footerLabel)
        layer.contentsScale = UIScreen.mainScreen().scale
        footerLabel.frame = CGRect(x: 0, y: 60, width: bounds.width, height: 40)
        footerLabel.textColor = UIColor.grayColor()
        footerLabel.textAlignment = .Center
        footerLabel.font = UIFont.systemFontOfSize(12)
    }
    override init(raisedWithFrame frame: CGRect) {
        super.init(raisedWithFrame: frame)
    }
    override init(flat: ()) {
        super.init(flat: ())
    }
    override init(flatWithFrame frame: CGRect) {
        super.init(flatWithFrame: frame)
    }
    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
}

class UserCountButton: UserButton {
    let countLabel = UILabel()
    override init() {
        super.init()
        addSubview(countLabel)
        countLabel.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 90)
        countLabel.textColor = UIColor.darkGrayColor()
        countLabel.textAlignment = .Center
        countLabel.font = UIFont.systemFontOfSize(32)
    }
    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
}

这是一个错误还是一些什么?我该如何解决? (我正在使用Xcode 6 Beta 5)

1 个答案:

答案 0 :(得分:0)

据我所知,问题在于您正在尝试更改countLabel上的内容,但您已通过let对其进行了定义,这使其无法变通。尝试将其更改为var,然后设置其所有属性。

此外,应该注意的是,我相信您需要在致电addSubview之前对UserCountButtonUserButton进行所有子视图初始化。