带有 setImage 的自定义 UIButton 不可点击

Custom UIButton with setImage not clickable

我有一个自定义的 uibutton,在自定义的 uibutton 中,我传递了一个带有图像名称的 viewModel,它只是调用 setImage.The addTarget 函数不是 working.What 我在这里遗漏了我试图禁用视图上的用户交互,因为我在它上面设置了一个图像视图。

CustomButton.swift

class CustomButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        clipsToBounds = true
        layer.cornerRadius = 9
        layer.borderWidth = 0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func configure(with viewModel: CustomButtonViewModel ){
        translatesAutoresizingMaskIntoConstraints = false

        setImage(UIImage(named: viewModel.image), for: .normal)

        self.imageView?.contentMode = .scaleToFill
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
}
struct CustomButtonViewModel {
    let image : String

}

ViewController.swift

class ViewController: UIViewController {
        //Spinner
        // intiate uibuttons
       
    
        
        override func viewDidLoad() {
            super.viewDidLoad()
            let imageView = UIImageView(image: UIImage(named: "bg.png"))
            imageView.isUserInteractionEnabled = false
            view = imageView
        
            let dogsButton = CustomButton(frame: CGRect(x: 20, y: 100, width: 140, height: 130))
            let catsButton = CustomButton(frame: CGRect(x: 200, y: 100, width: 140, height: 130))
            dogsButton.configure(with: CustomButtonViewModel(image: "dogs.png"))
            catsButton.configure(with: CustomButtonViewModel(image: "cats.png"))
            
            
            dogsButton.addTarget(self, action: #selector(dogsButtonClicked(sender:)), for: .touchUpInside)
            catsButton.addTarget(self, action: #selector(catsButtonClicked), for: .touchUpInside)
            view.addSubview(dogsButton)
            view.addSubview(catsButton)
            
        }
        @objc func dogsButtonClicked(sender : UIButton){
            print("dogs button clicked")
    //        let vc = CollectionViewController()
    //        let navVC = UINavigationController(rootViewController: vc)
    //        navVC.modalPresentationStyle = .fullScreen
    //        present(navVC, animated: true)
            
        }
        @objc func catsButtonClicked(){
            let vc = CollectionViewController()
            navigationController?.pushViewController(vc, animated: true)
            
        }
       
    }

您正在将 UIImageView 分配给 UIViewController 的基本视图并将其 isUserInteractionEnabled 属性 设置为 false,这将禁用用户交互它的所有子视图,包括您的按钮。您只需将此 属性 设置为 true,触摸事件就会起作用:

imageView.isUserInteractionEnabled = true