[英]AddTarget connected to UIButton in customView does not work. (swift5, iOS)
有一個帶有 UIButton 的自定義 UIView。 viewController 嘗試通過 addTarget(...) 將該函數連接到該 UIButton。 但它不起作用。
class customView: UIView {
var button: UIButton = {
//some properties
}()
}
class viewController: UIViewController {
var cv = customView()
override func viewDidLoad() {
cv.button.addTarget(self, action: #selector(someFunction), for: .touchUpInside)
}
@objc func someFunction() {
print("Some function!")
}
}
這段代碼不是我正在寫的。 但它是我正在編寫的代碼的一個非常簡短的表示。 觸摸按鈕時 SomeFunction 不起作用。 還需要什么?
很難在簡化的示例代碼上找出實際問題,即不是在自身上運行。 addTarget 本身的使用很好,所以我想問題出在代碼的某個地方,我們在這里沒有看到。
一個有根據的猜測可能是自定義視圖的大小/布局有問題。 根據視圖的不同,視圖的邊界可能小於按鈕或為零,盡管您仍然會看到完整的按鈕,但您無法單擊它。 如果在單擊按鈕時沒有在按鈕上獲得任何顏色效果,您可能會在標准按鈕上注意到這一點。
另一個好的下一步是查看 Xcode 的 View Debugger 以查看視圖大小是否有任何問題。
作為參考,我對您的示例代碼進行了一些編輯,使其在 Playground 中運行,並且您的函數在那里觸發得很好。
import PlaygroundSupport
import UIKit
class CustomView: UIView {
var button = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 20.0))
override init(frame: CGRect) {
super.init(frame: frame)
button.backgroundColor = .blue
button.setTitle("click me", for: .normal)
addSubview(button)
button.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
button.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController {
var customView = CustomView()
override func viewDidLoad() {
customView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(customView)
customView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
customView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
customView.button.addTarget(self, action: #selector(someFunction), for: .touchUpInside)
}
@objc func someFunction() {
print("Some function!")
}
}
PlaygroundPage.current.liveView = ViewController()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.