自定义UIButton子类不显示标题



让我首先说,我知道这是一个经常被问到的问题,我似乎找不到和我有同样情况/问题的人。

我正在写一个音乐应用程序,我想出了一个我喜欢的用户界面。它需要一个具有特殊功能的按钮(超过了自定义按钮类型可以实现的功能),所以我决定制作一个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)
}

也许添加[super layoutSubviews];我也遇到了同样的问题,因为我忘了加这一行。之后,您可以添加所需的代码。

我不知道为什么,但问题是将添加图像视图的代码放在layoutSubviews中——无论如何,这不是一个好地方,因为它可以被多次调用,这将导致您添加多个图像视图。如果将该代码移到initWithCoder方法中,它将正常工作。这是我做的测试课,

import UIKit
class RDButton: UIButton {
    var activeState: Bool
    var activeAccidental: UIImageView
    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: "img.jpg")
        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)
    }
}

当当前视图控制器(包含自定义按钮)从除main之外的队列中使用performSegue(withIdentifier:sender:)启动时,也会发生这种情况。要解决此问题,只需调用主线程中的方法。例如:

class MyViewController: ViewController {
    ...
    func doTask() {
        let myTask = MyTask()
        myTask.perform( {
            Dispatch.main.async {
                self.performSegue(withIdentifier: "second", sender: nil)
            }
        })
    }
}

最新更新