2017-01-22 64 views
0

我正在構建一個小型iOS應用程序,它涉及在tex文本字段更改時執行某些操作。我一直在試圖弄清楚如何在發生測試更改事件時編寫某些函數,但這些解決方案都不適用於我,我相信它們已經過時。最流行的解決方案是這樣的:在文本字段中處理測試更改的事件swift

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) 

func textFieldDidChange(_ textField: UITextField) { 

} 

此溶液張貼在這裏:How do I check when a UITextField changes?

然而當我嘗試實現這個我的代碼,我得到一個錯誤,指出價值成員UITextView沒有成員addTarget。我不確定代碼是否有錯,或者如果我寫錯了地方,我仍然很快學習,所以我很抱歉,如果有明顯的錯誤。 這裏是我的代碼:

import UIKit 

class JournalEntryViewController: UIViewController 
{ 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     print(RatingSelection.selectedSegmentIndex) 
     let date = NSDate() 
     let calendar = NSCalendar.current 
     let hour = calendar.component(.hour, from: date as Date) 
     let minutes = calendar.component(.minute, from: date as Date) 
     print("minutes: ",minutes) 
     if (minutes == 16) 
     { 
      print("got in!!!") 
      print(TextField.text) 

     } 


     func textFieldDidChange(_ textField: UITextField) 
     { 
      print("text changed") 

     } 

// This line is the problem, I'm trying to add a text changed event to TextField 
     TextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) 





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

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    @IBOutlet weak var TodaysDate: UILabel! 

    @IBOutlet weak var RateDayLabel: UILabel! 

    @IBOutlet weak var RatingSelection: UISegmentedControl! 

    @IBOutlet weak var TextField: UITextView! 

} 

編輯:

我試着這樣做,這幾乎是該解決方案的副本,但聲明仍沒有得到打印時在TextView的文本更改

class JournalEntryViewController: UIViewController, UITextViewDelegate 
{ 


    override func viewDidLoad() 
    { 

     super.viewDidLoad() 
     self.textField.delegate = self 

     func textViewDidChange(_ textView: UITextView) 
     { 
      print("text changed!!!") 
     } 


    } 

    override func didReceiveMemoryWarning() 
    { 
     super.didReceiveMemoryWarning() 
    } 


    @IBOutlet weak var textField: UITextView! 

    @IBOutlet weak var todaysDate: UILabel! 

    @IBOutlet weak var rateDayLabel: UILabel! 

    @IBOutlet weak var ratingSelection: UISegmentedControl! 


} 

任何人都可以請幫忙嗎?

編輯2: 我想出了問題,它不是在這個代碼。 感謝您的幫助!

回答

2

TextField變量(這應該是textField - 使用變量小寫首字母,大寫的類第一個字母)是UITextView,不是UITextField所以你嘗試使用不正確的解決方案。

對於需要實現合適的UITextViewDelegate方法UITextView

class JournalEntryViewController: UIViewController, UITextViewDelegate 
{ 

    override func viewDidLoad() 
    { 
     super.viewDidLoad() 
     self.textField.delegate = self 
    } 

    func textViewDidChange(_ textView: UITextView) { 
     // Do whatever 
    } 
} 
+0

評論張貼在後期編輯 –

+0

你已經把你的委託方法*裏面*'viewDidLoad'。它應該在任何其他功能之外 – Paulw11

相關問題