[英]How to read text from UITextInput in swift?
I am a beginner in swift.我是 swift 的初学者。 I have我有
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
}
}
How to get it ?如何获得? Help please.请帮忙。 Thanks in advance!!!!提前致谢!!!!
Swift 3:斯威夫特 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")
I got it.我知道了。
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
Your textInput
variable is never declared properly.您的textInput
变量从未正确声明。 You might want to consider learning more general practices of Swift before asking specific questions.在提出具体问题之前,您可能需要考虑学习更一般的 Swift 实践。
Proper declaration of textInput
would look like: textInput
正确声明如下所示:
class A : UIViewController {
var textInput: UITextInput
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) }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.