2015-09-26 150 views
0

發佈:textfield shouldChangeCharactersInRange not called

文本字段不接受字符。

shouldChangeCharactersInRange不被所有3個文本字段調用。

我有3個代表類實施就像在main。在main中實施與代理方法一樣的所有方法。在運行期間調用除shouldChangeCharactersInRange之外的所有其他方法。編輯框根本不接受任何字符。

import UIKit 

class ViewController: UIViewController , UITextFieldDelegate{ 

    @IBOutlet weak var textField1: UITextField! 
    @IBOutlet weak var textField2: UITextField! 
    @IBOutlet weak var textField3: UITextField! 

    var t1Delegate : text1Delegate! 
    var t2Delegate : text2Delegate! 
    var t3Delegate : text3Delegate! 

    override func viewDidLoad() { 
      t2Delegate = text2Delegate() 
     textField2.delegate = t2Delegate 
    } 
    override func viewDidAppear(animated: Bool) { 
     textField1.delegate = self 
     textField1.becomeFirstResponder() 
     t3Delegate = text3Delegate() 
     textField3.delegate = t3Delegate 
     super.viewDidLoad() 
    } 
    func textField (textField : UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String ) -> Bool { 
     print("*. Should change text.") 
     return true; 
    } 
    // UITextField Delegates 
    func textFieldDidBeginEditing(textField: UITextField) { 
     print("*. TextField did begin editing method called") 
    } 
    func textFieldDidEndEditing(textField: UITextField) { 
     print("*. TextField did end editing method called") 
    } 
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool { 
     print("*. TextField should begin editing method called") 
     return true; 
    } 
    func textFieldShouldClear(textField: UITextField) -> Bool { 
     print("*. TextField should clear method called") 
     return true; 
    } 
    func textFieldShouldEndEditing(textField: UITextField) -> Bool { 
     print("*. TextField should end editing method called") 
     return true; 
    } 

    func textFieldShouldReturn(textField: UITextField) -> Bool { 
     print("*TextField should return method called") 
     textField.resignFirstResponder(); 
     return true; 
    } 
} 
+2

使用,在你的代碼中的'shouldChangeCharactersInRange'委託方法纔會被調用的'textField1'。 – rmaddy

+0

你連接了IBOutlets嗎? –

+0

是的,每個IBOutlet(來自宣言行左側的小點)連接到故事板中的每個文本字段。 – theMobDog

回答

0

在Swift 3.0中改變Textfield編輯方法。 請在下面連接方法

class PromoCodeViewController: UIViewController , UITextFieldDelegate{ 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tf_GiftVoucher.delegate = self 

    // Do any additional setup after loading the view. 
} 

func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool { 
    if tf_GiftVoucher == textField { 
     let text = textField.text 
     if (text?.characters.count)! > 15 || string == " " { 
      return false 
     } 
    } 
    return true 
} 
根據您所提供的代碼