2017-08-09 24 views
1

我使用SWIFT 3,我有一个类,如下所示:UITextViewDelegate

class Assistor : NSObject , UITextViewDelegate { 


private override init() { 

} 

class func RegisterTextView(uiview:UIView) { 

    if let RegisteredView = uiview as? UITextView { 
     RegisteredView.delegate = self as! UITextViewDelegate 
    } 
} 


func textViewDidBeginEditing(_ textView: UITextView) { 
    print("Begin") 
} 

func textViewDidEndEditing(_ textView: UITextView) { 
    print("End") 
} 
} 

从一个正常的UIViewController我要调用的辅助器功能像这样在viewDidLoad中:

class InqueryDetailsViewController: UIViewController { 
    @IBOutlet weak var AnswerTextView:UITextView! 
override func viewDidLoad() { 
    super.viewDidLoad() 

Assistor.RegisterTextView(uiview: AnswerTextView) 
} 
} 

很明显,我想从助理触发textViewDidBeginEditing,而不是从uiviewcontroller中触发。怎么做?

+1

你的代码在哪里声明并初始化你的'Assistor'?并且你的RegisterTextView必须是一个实例func –

+0

我编辑了这个问题,以便你可以看到调用的uiviewcontroller。 – FamousMaxy

回答

1

首先你Assistor必须声明为对象,如果你只想要一个你可以把它作为单,您需要在init变更为公开,并改变registerTextView作为实例方法

尝试用这种

class Assistor : NSObject , UITextViewDelegate { 

    //Singleton 
    static let sharedInstance: Assistor = Assistor() 

    override init() { 
     super.init() 
    } 

    func registerTextView(uiview:UIView) { 
     if let RegisteredView = uiview as? UITextView { 
      RegisteredView.delegate = self as! UITextViewDelegate 
     } 
    } 


    func textViewDidBeginEditing(_ textView: UITextView) { 
     print("Begin") 
    } 

    func textViewDidEndEditing(_ textView: UITextView) { 
     print("End") 
    } 
} 

使用它

class ViewController: UIViewController { 

    @IBOutlet weak var textView: UITextView! 

    var assistor : Assistor = Assistor() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.assistor.registerTextView(uiview: self.textView) 
     //using as singleton 
     //Assistor.sharedInstance.registerTextView(uiview: self.textView) 
    } 
} 

希望这有助于

+0

使用单身人士的部分作为魅力。多谢兄弟。从我的阅读 – FamousMaxy

+0

我知道,不建议使用单身。这是否适用于上述情况?从我的阅读 – FamousMaxy

+0

我知道,不建议使用单身。这是否适用于上述情况? – FamousMaxy

相关问题