2024-11-24
protocol CanDealWithUITextFields{
func textFieldDidBeginEditing()
}
这样一来,每个应用这个protocol的子类就必须拥有这些textField的生命周期function,而且必须在自己类的内部定义。
事实上,这个protocol叫做UITextFieldDelegate
。
protocol UITextFieldDelegate{
func textFieldDidBeginEditing()
}
// UITextFieldDelegate 的简化定义(实际上是 Objective-C 定义的)
@objc protocol UITextFieldDelegate: NSObjectProtocol {
// 注意 @objc optional 关键字
@objc optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
@objc optional func textFieldDidBeginEditing(_ textField: UITextField)
@objc optional func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
@objc optional func textFieldDidEndEditing(_ textField: UITextField)
// ... 还有更多方法
}
这样一来,所有UITextField就可以复用这些method
var delegate: UITextFieldDelegate //property
delegate.textFieldDidBeginEditing() //method
let textField = UITextField()
textField.delegate = self //即等于类自己,所以可以重新定义protocol的相关方法
func textFieldDidBeginEditing(){
//do something
}
能做什么
,即have the functions.怎么做
,即define the function.谁来做
,即call the function.过程示例:
protocol AdvancedLifeSupport{
func performCPR()
}
class EmergencyCallHandler{
var delegate: AdvancedLifeSupport?
func assessSituation(){
print("Can you tell me what happened?")
}
func medicalEmergency(){
delegate?.performCPR()
}
}
struct Parametic: AdvancedLifeSupport{
init(handler: EmergencyCallHandler){
handler.delegate = self
}
func performCPR() {
print("The paramedic does chest compressions, 30 per second.")
}
}
class Doctor: AdvancedLifeSupport{
init(handler: EmergencyCallHandler){
handler.delegate = self
}
func performCPR() {
print("The doctor does chest compressions, 30 per second.")
}
func useStethescope(){
print("Listening for heart sounds.")
}
}
class Surgeon: Doctor{
override func performCPR() {
super.performCPR()
print("Sings stying alive by the BeeGees.")
}
func useElectricDrill(){
print("Whirr..")
}
}
let emilio = EmergencyCallHandler()
//let pete = Parametic(handler: emilio)
let angela = Surgeon(handler: emilio)
emilio.assessSituation()
emilio.medicalEmergency()