【问题标题】:Custom UITextViewDelegate/UITextFieldDelegate not called未调用自定义 UITextViewDelegate/UITextFieldDelegate
【发布时间】:2016-12-21 01:07:45
【问题描述】:

正在尝试为 UITextViewDelegateUITextFieldDelegate 创建自定义委托类。当我将这些类设置为它们自己的委托,或将另一个 UIKit 组件设置为它们的委托时,一切正常。但是,如果我创建自己的类作为委托,则永远不会调用委托方法。为什么?

这行得通:

class MyTextView: UITextView, UITextViewDelegate {
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.delegate = self
}

func textViewDidChange(_ textView: UITextView) {
  print("I work")
}

这不是:

class MyTextView: UITextView {
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.delegate = MyDelegate()
}

class MyDelegate: NSObject, UITextViewDelegate {
  func textViewDidChange(_ textView: UITextView) {
    print("I work")
  }
}

注意:如果MyDelegate不是NSObject的子类,则会抛出以下错误:

/// Type 'MyDelegate' does not conform to protocol 'NSObjectProtocol'

【问题讨论】:

  • 您好,您需要保留对 MyDelegate 类的引用,否则它将获得 dealloc。
  • #Facepalm!我刚刚在另一堂课上遇到了这个问题。试一试;谢谢!
  • @koropok 回过头来看,delegate 字段本身不应该保持对 MyDelegate 的引用吗?
  • 在通常的 Cocoa/Cocoa Touch 类中,delegate 只保留弱引用。为了使委托正常工作,需要将其保存在具有强引用的其他地方。
  • 我刚刚测试过,保持强引用会起作用,就像@OOPer 所说的那样。

标签: ios swift delegates swift3


【解决方案1】:

当您在第二种情况下设置文本字段委托时,您正在创建 MyDelegate() 类的弱引用。您可以检查以下代码,这将通过创建 MyDelegate() 的强引用来解决您的问题。

class MyTextView: UITextView {
    var responseDelegate = MyDelegate()
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = responseDelegate
    }
}
class MyDelegate: NSObject, UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        print("I work")
    }
}

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2015-09-13
    • 2013-11-05
    相关资源
    最近更新 更多