addTarget()在自定义扩展名上不起作用

时间:2018-12-14 08:43:35

标签: swift

我创建了一个自定义UIView(),并尝试向其中添加一个okButton。

但是。我已经添加了按钮,但是当在我的一个ViewController中显示UIView时,该按钮将不起作用。这是我的代码:

class Luna: UIView {

let luna = UIView()
let okButton = UIButton()
typealias completionHandler = (_ success:Bool) -> Void


// Not yet implemented
open var touchOutsideToHide: Bool = true;

private var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}


override init(frame: CGRect) {
    super.init(frame: frame)
    okButton.setTitleColor(.blue, for: .normal)
    okButton.setTitle("Okay", for: .normal)
    okButton.titleLabel?.font = UIFont(name: "avenirnext-demibold", size: 16)

    let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.pressButton(_:)))
    okButton.addGestureRecognizer(gesture)
}

required public init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

}

}

 //The target function
@objc func pressButton(_ sender: UIButton){ //<- needs `@objc`
    // .. //
    print("btn hit")
}

我在控制台中没有收到btn hit,并且水龙头未注册

该按钮是可见的,它已添加为子视图: Screenshot

1 个答案:

答案 0 :(得分:0)

按钮具有默认的触摸手势,您无需添加它。只需按照以下步骤添加目标即可解决您的问题。创建您的客户类别的协议,并在以下相同的类别中为其声明委托。

protocol LunaDelegate: class {
    func okButtonTapped(sender: UIButton)
}

class Luna: UIView {

    let luna = UIView()
    let okButton = UIButton()
    typealias completionHandler = (_ success:Bool) -> Void

    weak var delegate: LunaDelegate?

    // Not yet implemented
    open var touchOutsideToHide: Bool = true;

    private var screenWidth: CGFloat {
        return UIScreen.main.bounds.width
    }


    override init(frame: CGRect) {
        super.init(frame: frame)
        okButton.setTitleColor(.blue, for: .normal)
        okButton.setTitle("Okay", for: .normal)
        okButton.titleLabel?.font = UIFont(name: "avenirnext-demibold", size: 16)
        okButton.addTarget(self, action: #selector(pressButton(sender:)), for: .touchUpInside)
}

@IBAction func pressButton(sender: UIButton) {
    if let selfDelegate = self.delegate {
        selfDelegate.okButtonTapped(sender: sender)
    }
}

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

然后按照以下说明实施代码以使用自定义视图。当您按下按钮时,将在视图控制器中调用委托方法。

用法:

class LunaViewController: UIViewController, LunaDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let luna = Luna(frame: CGRect.init(x: 100, y: 100, width: 100, height: 40))
        luna.delegate = self
        self.view.addSubview(luna)
    }

    // MARK:- Luna Delegate
    func okButtonTapped(sender: UIButton) {
        print("OK Button Pressed From Luna View")
    }
}

这是我在当前项目中已经使用的正确解决方案。希望对您有帮助。