首页 > 解决方案 > 如何将目标添加到扩展中的按钮?

问题描述

如果我的视图控制器为空,我编写了一个扩展来显示空状态。我还想添加一个带有目标的UIButton() 。如何在扩展中为我的按钮实现addTarget操作?(Fe 一个简单的“Hello World”或我需要的任何东西)

extension UITableView{

    func setEmptyView(title: String, message: String) {

     // handling states

        button.setTitle("+ Add New Documentation", for: .normal)
        button.titleLabel!.font = UIFont(name: "Roboto-Regular", size: 24)
        button.setTitleColor(UIColor(hex: "BDC86F"), for: .normal)
        button.backgroundColor = UIColor(hex: "506182")
       button.addTarget...

    //more code
     emptyView.addSubview(button) 
    }
}

标签: iosswift

解决方案


我已经实现了同样的UIView扩展。希望,它会帮助你,我假设你能够将它转换为UITableView

代码:

extension UIView{
    
    func setEmptyView(title: String, message: String) {
        let emptyView = UIView(frame: self.bounds)
        // handling states
        let button = UIButton(frame: emptyView.bounds)
        button.setTitle("+ Add New Documentation", for: .normal)
        button.titleLabel!.font = UIFont(name: "Roboto-Regular", size: 24)
        button.setTitleColor(UIColor.red, for: .normal)
        button.backgroundColor = UIColor.black
        button.addTarget(self, action: #selector(btnTapEvent(sender:)), for: .touchUpInside)
        emptyView.addSubview(button)
        //more code
        self.addSubview(emptyView)
    }
    
    @objc func btnTapEvent(sender:UIButton){
        print("btnTapEvent")
    }
}

参考图片:

在此处输入图像描述


推荐阅读