【问题标题】:How to read text from UITextInput in swift?如何快速从 UITextInput 读取文本?
【发布时间】:2016-01-28 15:18:40
【问题描述】:

我是 swift 的初学者。 我有

class A : UIViewController {
var textInput: UITextInput

init(textInput: UITextInput) {
    self.textInput = textInput
}

func getText() -> String() {
    /// Here I need to get the current text from textInput
}

}

如何获得?请帮忙。提前谢谢!!!!

【问题讨论】:

  • 大家好.. 我终于找到了

标签: ios swift uitextinput


【解决方案1】:

斯威夫特 3:

let start  = sender.beginningOfDocument
let end = sender.endOfDocument
let range = sender.textRange(from: start, to: end)!

let trimmedText = sender.text(in: range)
sender.replace(range, withText: "new text")

【讨论】:

    【解决方案2】:

    我明白了。

    let start: UITextPosition  = self.textInput.beginningOfDocument
    let end: UITextPosition = self.textInput.endOfDocument
    let range: UITextRange = textInput!.textRangeFromPosition(start!, toPosition: end!)!
    textInput!.textInRange(range!) // for get text
    textInput.replaceRange(range!, withText: "some text") // to write text
    

    【讨论】:

      【解决方案3】:

      您的textInput 变量从未正确声明。在提出具体问题之前,您可能需要考虑学习更多通用的 Swift 实践。

      textInput 的正确声明如下所示:

      class A : UIViewController {
          var textInput: UITextInput
      

      【讨论】:

      • 我将一个 textView 或 textField 传递给这个 init()。他们正在其他控制器中进行初始化。你能帮我如何使用 UITextInput 吗?
      • 为什么不使用UITextField 并使用textInput.text 获取文本?
      • 对,为什么不用UITextField
      【解决方案4】:
      import Foundation
      import UIKit
      
      public extension UITextInput {
          public var text: String {
              get { text(in: textRange(from: beginningOfDocument, to: endOfDocument)!) ?? "" }
              set(value) { replace(textRange(from: beginningOfDocument, to: endOfDocument)!, withText: value) }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多