UIButton子类无法分配目标-Swift 4

时间:2018-09-16 08:14:00

标签: ios swift uibutton swift4

我查看了类似问题的其他各种答案,并按照那里给出的建议进行了操作,但是在这里我没有遇到任何错误,但是目标函数从未运行。

我有这个UIButton子类

class RoundedButton: UIButton {

var buttonColour: UIColor = UIColor.red
var height: CGFloat = 0
var width: CGFloat = 0
var text: String = ""
var x: CGFloat = 0
var y: CGFloat = 0

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

init(frame: CGRect, colour: UIColor, height: CGFloat, text: String, width: CGFloat, x: CGFloat, y: CGFloat) {
    super.init(frame: frame)
    self.buttonColour = colour
    self.height = height
    self.text = text
    self.width = width
    self.x = x
    self.y = y
    setUpView()
}



func setUpView() {
    let roundedButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: height))
    roundedButton.backgroundColor = buttonColour
    roundedButton.setTitle(text, for: .normal)
    roundedButton.setTitleColor(UIColor.white, for: .normal)
    roundedButton.layer.cornerRadius = 4
    roundedButton.addTarget(self, action: #selector(self.wasPressed(_:)), for: .touchUpInside)
    self.addSubview(roundedButton)
}



@objc func wasPressed(_ sender: UIButton) {
    print("was pressed")
}

}

我这样称呼它:

let addReview = RoundedButton(frame: CGRect(), colour: #colorLiteral(red: 0.9921568627, green: 0.6941176471, blue: 0.2, alpha: 1), height: 48, text: "Review", width: UIScreen.main.bounds.width - 16, x: 8, y: UIScreen.main.bounds.maxY - 56)
                self.view.addSubview(addReview)

但是wasPressed(_ sender:UIButton)函数从不打印“被按下”。有人知道为什么会这样吗?

还可以添加目标,以便在超类中将其称为“动态”目标。 例如,我可以每次向子类发送不同的目标。

这是为了让我可以使用RoundedButton类制作多个按钮。

1 个答案:

答案 0 :(得分:1)

您不必在func setUpView()内添加另一个按钮,因为您已经在按钮子类中,因此可以直接配置其属性,您声明的所有属性都已经存在于按钮中

class RoundedButton: UIButton {

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

    init(frame: CGRect, colour: UIColor, text: String) {
        super.init(frame: frame)

        self.backgroundColor = colour
        self.setTitle(text, for: .normal)
        self.setTitleColor(UIColor.white, for: .normal)
        self.layer.cornerRadius = 4
        self.addTarget(self, action: #selector(self.wasPressed(_:)), for: .touchUpInside)

    }

    @objc func wasPressed(_ sender: UIButton) {
        print("was pressed")
    }

}

//

let addReview = RoundedButton(frame: CGRect(x:8,y:UIScreen.main.bounds.maxY - 56,width: UIScreen.main.bounds.width - 16, height: 48), colour: #colorLiteral(red: 0.9921568627, green: 0.6941176471, blue: 0.2, alpha: 1), text: "Review" )
self.view.addSubview(addReview)