自定义UI按钮上的addTarget无法以编程方式工作

问题描述 投票:0回答:2

我使用此初始化程序创建了一个自定义UIButton:

class CustomButton : UIButton{


override init(frame: CGRect) {
    super.init(frame: frame)
    setUpButtoninClass(frame)

    addTarget(self, action: #selector(handleTap), for:.touchUpInside )

}




fileprivate func setUpButtoninClass(_ frame: CGRect) {
    let padding : CGFloat = 16



    self.frame = frame
    layer.shadowColor = UIColor.darkGray.cgColor
    layer.shadowOpacity = 0.3
    layer.shadowOffset = .zero
    layer.shadowRadius = 10
    layer.cornerRadius = frame.width/2
    backgroundColor = UIColor(white: 0.9, alpha: 1)

    let buttonView = UIView(frame: frame)

    buttonView.layer.cornerRadius = frame.width/2
    buttonView.backgroundColor = .white
    addSubview(buttonView)

    let imageView = UIImageView(image: UIImage(named: "pen")?.withRenderingMode(.alwaysTemplate))
    imageView.tintColor = UIColor(white: 0.7, alpha: 1)
    buttonView.addSubview(imageView)
    imageView.anchor(top: buttonView.topAnchor, leading: buttonView.leadingAnchor, bottom: buttonView.bottomAnchor, trailing: buttonView.trailingAnchor, padding: UIEdgeInsets.init(top: padding, left: padding, bottom: padding, right: padding))

}

@objc func handleTap(){
    print("I'm here")
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")

}}

在初始化程序中,我添加了一个目标,但是当我实际上在VC中初始化自定义按钮时,#selector方法(handleTap)未调用

这是VC中自定义Button的实现:

class ViewController: UIViewController {


let circularButton = CustomButton(frame: CGRect(x: 0, y: 0, width: 70, height: 70))


override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(circularButton)
    circularButton.center = view.center
}

我还尝试在VC中初始化CustomButton时添加目标,但未做任何更改。我想知道我在设置按钮时出错了。

编辑1:这是“调试视图”层次结构Debug Hierarchy

ios swift uibutton uikit addtarget
2个回答
0
投票
我认为这是你的错,未检测到触摸,因为您已将ImageView添加到UIButton的顶部。试试这个,或者这个,

0
投票
OMG,调试代码后,buttonViewimageView在顶部。按钮是隐藏的。您可以设置颜色以更轻松地对其进行调试。删除上面的2个视图,使您的代码运行完美]
© www.soinside.com 2019 - 2024. All rights reserved.