我正在使用swift 3,我有一个类如下:
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中调用这样的Assistor函数:
class InqueryDetailsViewController: UIViewController {
@IBOutlet weak var AnswerTextView:UITextView!
override func viewDidLoad() {
super.viewDidLoad()
Assistor.RegisterTextView(uiview: AnswerTextView)
}
}
很明显,我想从助手中触发textViewDidBeginEditing,而不是从uiviewcontroller触发。怎么做?
答案 0 :(得分:1)
首先必须将Assistor
声明为对象,如果只需要一个可以将其设为单例,则需要将init更改为public,并将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)
}
}
希望这有帮助