为什么我的委托只在定义为VC而不是外部类时才起作用?

时间:2016-02-13 08:41:27

标签: ios xcode swift delegates

关于如何将textField限制为特定长度和字符集

,我已遵循此tutorail

这是我的代码,但代表没有被调用:

VC类:调用它(在调试时验证)

import UIKit
import CoreLocation

public class InlineMainViewController: UIViewController, CLLocationManagerDelegate, UITextFieldDelegate, MainUiDelegate {

   ...

    var nameTextVerifier = NameTextVerifier()
    @IBOutlet weak var enterName_text: UITextField!
...

override public func viewDidLoad() {
    enterName_text.delegate = nameTextVerifier
    }

NameTextVerifier类:

    import Foundation

    public class NameTextVerifier: NSObject, UITextFieldDelegate {

        public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
            if string.characters.count == 0 {
                return true
            }
             let currentText = textField.text ?? ""
            let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string)


                return prospectiveText.containsOnlyCharactersIn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") &&
                    prospectiveText.characters.count <= 6
              }
    }

当我输入enterName_text

时,永远不会调用此代码

另一方面,当我在VC类中放置相同的shouldChangeCharactersInRange并将VC设置为委托时

func onViewDidLoad(){     enterName_text.delegate = self     }

使shouldChangeCharactersInRange执行

我该如何检查问题是什么?

1 个答案:

答案 0 :(得分:0)

你不能在NameTextVerifier的地方使用TextManager

var nameTextVerifier = TextManager()
in place of
var nameTextVerifier = NameTextVerifier()