Access a textfield from a class


I have a class created in cocoa to draw some straight lines on the screen, I run the application and draw everything in the coordinates I give it. However I want to be able to assign the values from a textfield that is in the viewcotroller , but I get an error.

First in the class I create the object like this:

 var texto:ViewController? 

then I initiate the object and when I want to read the property text I get an error, that's how I read it:

texto = ViewController()
leeTexto = texto?.valores.text

Now when I want to call the show I do it like this:

@IBAction func angulo(sender: UIButton) {
    let recta = CGRect(x: 0, y: 0, width: 512, height: 512)
    objetoDibujo = DrawExamples()

and this is the structure of the function:

override func drawRect(rect: CGRect) {

I attach the error image:

asked by jose luis ruelas garcia 22.09.2016 в 19:38

3 answers


If the problem with the expression texto?.valores.text is that it found nil , the only thing that can be nil is valores ...

I suggest you check the initialization of the variable valores in the class ViewController .

In any case, if valores can be nil , you should write it as:

leerText = texto?.valores?.text

or like this:

if let valores = texto?.valores {
    leerTexto = valores.text
answered by 22.09.2016 в 21:18

It seems that you are incorrectly initializing the ViewController texto . In the capture that you uploaded, it is shown that the variable valores has in @IBOutlet , so it is related to a storyboard or a .nib file.

Assuming that you are using the default configuration, that is, a UIStoryboard called Main that inside has a UIViewController called ViewController, you must use the following code:

let storyboard = UIStoryboard(named: "Main", bundle: nil)
let texto = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController

Otherwise, if the ViewController is inside a nib file (let's assume it is called ViewController.xib), you must initialize it as follows:

let texto = NSBundle.mainBundle().loadNibNamed("ViewController", owner: nil, options: nil).first as! ViewController
answered by 13.10.2016 в 04:02

When initializing the string, you should put it in the following way

var cadena: String = ""

and when you are going to read what has a textfield you must avoid that the value is null with the following

cadena = textfield.text! // El signo de exclamación forza que sea texto y no nil

I hope you help, greetings!

answered by 20.10.2016 в 16:07