[英]How to read text from UITextInput in swift?
我是 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
}
}
如何獲得? 請幫忙。 提前致謝!!!!
斯威夫特 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")
我知道了。
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
您的textInput
變量從未正確聲明。 在提出具體問題之前,您可能需要考慮學習更一般的 Swift 實踐。
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.