【发布时间】:2015-01-07 14:16:17
【问题描述】:
首先让我说我知道这是一个经常被问到的问题,但我似乎找不到与我有相同情况/问题的人。
我正在编写一个音乐应用程序,我想出了一个我喜欢的 UI。它需要一个具有特殊功能的按钮(超越了自定义按钮类型可以实现的功能),所以我决定创建一个UIButton 子类。我在我的子类中使用了以下代码:
required init(coder aDecoder: NSCoder) {
self.activeState = false
self.activeAccidental = UIImageView()
super.init(coder: aDecoder)
self.layer.borderColor = UIColor(white:221/255, alpha: 1.0).CGColor
self.layer.borderWidth = 2.0
self.backgroundColor = UIColor.blackColor()
self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.setTitle("Hello", forState: .Normal)
}
override func layoutSubviews() {
println(self.frame.origin.x)
self.activeAccidental = UIImageView(frame: CGRectMake(self.bounds.origin.x, self.bounds.origin.y, 20, 20))
self.activeAccidental.image = UIImage(named: "BMICalcIcon.png")
self.addSubview(activeAccidental)
}
但是,当我向故事板添加按钮(并在字段中输入自定义类名称)时,无论是在初始化程序中设置,还是在故事板的属性检查器中设置,我的标题都是不可见的。这是我在 swift 中的第一个主要项目,所以我不完全确定问题出在哪里。
ImageView 移动到 initWithCoder 时的代码
required init(coder aDecoder: NSCoder) {
self.activeState = false
self.activeAccidental = UIImageView()
super.init(coder: aDecoder)
self.activeAccidental = UIImageView(frame: CGRectMake(self.bounds.origin.x, self.bounds.origin.y, 20, 20))
self.activeAccidental.image = UIImage(named: "BMICalcIcon.png")
self.layer.borderColor = UIColor(white:221/255, alpha: 1.0).CGColor
self.layer.borderWidth = 2.0
self.backgroundColor = UIColor.blackColor()
self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.setTitle("Hello", forState: .Normal)
self.addSubview(activeAccidental)
}
【问题讨论】:
-
图层的背景颜色和标题都是白色的。会不会是这个问题?
-
对不起,我一定是复制代码错了,我现在就修。
标签: ios swift uibutton subclass