簡體   English   中英

addTarget()在自定義擴展名上不起作用

[英]addTarget() does not work on custom extensions

我做了一個自定義的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 ,並且水龍頭未注冊

該按鈕可見,將其添加為子視圖: 屏幕快照

按鈕具有默認的觸摸手勢,您無需添加它。 只需按照以下步驟添加目標即可解決問題。 創建您的客戶類別的協議,並在以下相同的類別中為其聲明委托。

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")
    }
}

這是我在當前項目中已經使用的正確解決方案。 我希望這能幫到您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM