有没有办法在 self 以外的事物上使用addTarget
(这似乎是最常见的用例(?
是的,您可以使用self
以外的目标。 最常见的用法是使用self
调用addTarget
,其中self
是对将UIControl
添加到其视图层次结构的 viewController 的引用。 但是您不需要以这种方式使用它。target
只是对对象的引用,因此您可以向它传递对所需任何对象的引用。action
是一个Selector
,需要定义为该对象class
上的实例方法,并且该方法必须可用于Objective-C(用@objc
或@IBAction
标记(,并且它必须不带任何参数,只有sender
,或者sender
和event
。
您还可以将nil
作为目标传递,这会告诉 iOS 在响应程序链中搜索action
方法。
这里有一个小的独立示例:
import UIKit
class Foo {
@objc func buttonClicked() {
print("clicked")
}
}
class ViewController: UIViewController {
let foo = Foo()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 30))
button.setTitle("Press me", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(foo, action: #selector(Foo.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
}
}
您当然可以设置其他对象来接收控制操作。请考虑以下视图控制器:
首先,定义一个类,其工作是响应按钮点击操作:
@objc class ButtonTarget: NSObject {
@IBAction func buttonAction(_ sender: Any) {
print("In (#function)")
}
}
现在定义一个创建ButtonTarget
对象的视图控制器
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
lazy var buttonTarget = ButtonTarget() //Give the ViewController a `ButtonTarget`
override func viewDidLoad() {
super.viewDidLoad()
//Add a taret/action to the button that invokes the method `buttonAction(_:)`
button.addTarget(
buttonTarget,
action: #selector(ButtonTarget.buttonAction(_:)),
for: .touchUpInside)
}
}