Swift 代码,将打印在 UITextView 中键入的新单词的所有字符的字符串,因为它们正在被键入

Posted

技术标签:

【中文标题】Swift 代码,将打印在 UITextView 中键入的新单词的所有字符的字符串,因为它们正在被键入【英文标题】:Swift code that will print a string of all the characters of a new word typed in a UITextView as they are being typed 【发布时间】:2016-03-11 18:09:13 【问题描述】:

我需要有关将在 UITextView 函数 textViewDidChange 的主体中运行的 swift 代码或函数的帮助,当它们在 UITextView 控件中键入时,它将打印新 Word 的所有字母的字符串。因此,如果我的用户界面上有一个名为 txtTextView 的 UITextView 控件,并且当应用程序开始运行时它没有文本,如果我然后键入字母“o”,那么字母“o”将在控制台输出屏幕中打印。在我输入“或”后,将打印“或”。在我输入“橙色”后,将打印“橙色”。如果在输入 orange 后按空格键并开始输入“ma”,则将打印“ma”,在输入“orange mango”后,将打印“mango”。希望我已经传达了这个想法。基本上,我希望代码在 UITextView 中键入每个新单词时打印它们的所有字母。非常感谢您的帮助。

func textViewDidChange( textView: UITextView ) 
 // code for this place

【问题讨论】:

你试过print(textView.text)吗? 【参考方案1】:

只需为您的textField 创建一个出口,添加UITextViewDelegate 并设置委托。之后只需覆盖textViewDidChange 方法。下面的代码示例

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() 
    super.viewDidLoad()

    textView.delegate = self


@IBAction func textField_EditingChanged(sender: UITextField) 
    // Will print out each letter that is typed
    print(sender.text!.characters.last!)

    // Will print out the word
    print(sender.text!)


func textViewDidChange(textView: UITextView) 
    // Will print out each letter that is typed
    print(textView.text!.characters.last!)

    // Will print out the word
    print(textView.text!)

【讨论】:

以上是关于Swift 代码,将打印在 UITextView 中键入的新单词的所有字符的字符串,因为它们正在被键入的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 以编程方式居中 UITextView

Swift 3在UITextView中更改所选文本的颜色

当键盘出现在swift中时滚动UITextView

将键盘选择为中文(简体)时不调用 UITextView 委托 shouldChangeTextInRange - Swift 4.2 中的手写

Swift 3 - 限制 uitextview 中的字符数

当用户在 Swift 中点击 UITextView 时,如何运行一段代码?