簡體   English   中英

如果按鈕在自定義視圖中使用 let 和 addTarget 初始化,則 UIButton 的操作不起作用,但它在 UIViewController 中起作用

[英]Action of UIButton doesn't work if the button is initialized with let and the addTarget in it in custom view, but it works in UIViewController

當我在自定義視圖中創建如下所示的按鈕時該操作不起作用:

private let usernameButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitleColor(.black, for: .normal)
    button.setTitle("someTitle", for: .normal)
    button.titleLabel?.font = .boldSystemFont(ofSize: 13)
    button.addTarget(self, action: #selector(didTapUsername), for: .touchUpInside)
    return button
}()

但是,當我以某種方式在UIViewController 中執行相同操作時,它會起作用。

如果我讓它懶惰它總是有效但不明白為什么如果我讓它在自定義視圖中讓它在 UIViewController 中工作時它不起作用

感謝您的任何評論。

該塊內的self實際上是塊,而不是視圖(您可以使用print(self)看到它),可能是因為它尚未初始化(與您不能在super.init之前使用 self 的原因相同),這就是為什么我通常在初始化塊之外添加目標/委托。 lazy var self 已經初始化,所以應該沒有問題。

我不確定它為什么有效,對我來說似乎有點神奇,我不會依賴它。

無論如何,在我的情況下,它適用於自定義 ViewController 和自定義 View:我已將CustomView作為子視圖添加到情節CustomView中的ViewController

class ViewController: UIViewController {
    
    private let usernameButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitleColor(.black, for: .normal)
        button.setTitle("someTitle", for: .normal)
        button.titleLabel?.font = .boldSystemFont(ofSize: 13)
        button.addTarget(self, action: #selector(didTapUsername), for: .touchUpInside)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.insertSubview(usernameButton, at: 0)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        usernameButton.frame = view.bounds
    }
    
    @objc
    func didTapUsername() {
        print("ViewController", #function)
    }
}

class CustomView: UIView {
    private let usernameButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitleColor(.black, for: .normal)
        button.setTitle("someTitle", for: .normal)
        button.titleLabel?.font = .boldSystemFont(ofSize: 13)
        button.addTarget(self, action: #selector(didTapUsername), for: .touchUpInside)
        return button
    }()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        addSubview(usernameButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        usernameButton.frame = bounds
    }
    
    @objc
    func didTapUsername() {
        print("CustomView", #function)
    }
}

這對於UIViewController / UIView不應該有不同,請檢查您的邏輯

暫無
暫無

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

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