简体   繁体   中英

How to read text from UITextInput in swift?

I am a beginner in 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:

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. You might want to consider learning more general practices of Swift before asking specific questions.

Proper declaration of textInput would look like:

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) }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM