连接到customView中UIButton的AddTarget不起作用.(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的视图调试器,看看视图大小是否有问题。

作为参考,我对您的示例代码进行了一点编辑,使其在游乐场中运行,并且您的函数在那里被很好地触发。

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()

最新更新