addTarget(_:action:for:)
是 UIButton 的方法,用于将按钮的特定事件(如触摸事件)与目标对象的方法关联起来。当按钮事件触发时,系统会调用目标对象上指定的方法。
当 addTarget
到 UIView 的 Swift 类不起作用时,可能的原因包括:
@objc
要求或参数类型不匹配class MyView: UIView {
@objc func buttonTapped() {
print("Button tapped")
}
}
let button = UIButton()
let myView = MyView()
button.addTarget(myView, action: #selector(MyView.buttonTapped), for: .touchUpInside)
确保目标对象(MyView 实例)在按钮事件触发时仍然存在:
class ViewController: UIViewController {
let myView = MyView() // 保持强引用
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
button.addTarget(myView, action: #selector(MyView.buttonTapped), for: .touchUpInside)
view.addSubview(button)
}
}
button.isUserInteractionEnabled = true // 确保为true
button.isEnabled = true // 确保为true
import UIKit
class MyView: UIView {
@objc func handleButtonTap(_ sender: UIButton) {
print("Button tapped in MyView")
}
}
class ViewController: UIViewController {
let myView = MyView()
override func viewDidLoad() {
super.viewDidLoad()
// 设置myView的frame
myView.frame = CGRect(x: 50, y: 100, width: 200, height: 200)
myView.backgroundColor = .lightGray
view.addSubview(myView)
// 创建按钮
let button = UIButton(type: .system)
button.frame = CGRect(x: 50, y: 50, width: 100, height: 44)
button.setTitle("Tap Me", for: .normal)
button.backgroundColor = .white
// 添加按钮到myView
myView.addSubview(button)
// 添加目标动作
button.addTarget(
myView,
action: #selector(MyView.handleButtonTap(_:)),
for: .touchUpInside
)
}
}
@objc
isUserInteractionEnabled
和 isEnabled
属性.touchDown
替代 .touchUpInside
)如果上述方法都不奏效,可以尝试:
hitTest(_:with:)
方法检查触摸事件是否到达按钮allTargets
和 allControlEvents
属性通过以上方法,应该能够解决 UIButton.addTarget
到 UIView 子类不起作用的问题。
没有搜到相关的文章