0

I have this code here that runs an alertview and shows a textfield asking for the subject name

 alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
            var textf= alertController.textFields[0] as UITextField
            self.items += [self.textf]
            println(self.items)
            println(textf)
            self.view .setNeedsDisplay()

        }))

And then Im declaring the variables items and textf out of that function at the top of the code using this code

var items = ["English"]
let textf = ""

but the problem is that when I run my app and click on my button that shows the alertview and i type in my subject and click ok I get this error when it tries to print out string. It just prints out this error and it does not close my app

<_UIAlertControllerTextField: 0x7f9d22d1c430; frame = (4 4; 229 16); text = 'irish'; clipsToBounds = YES; opaque = NO; gestureRecognizers = <NSArray: 0x7f9d22cc55f0>; layer = <CALayer: 0x7f9d22d1c6e0>>

It says in the error the text I typed in but It is not adding it to the variable because when i print out the array items it prints out

[English, ]

and not

[English, irish]
4

1 回答 1

0

这很奇怪……

var textf= alertController.textFields[0] as UITextField
self.items += [self.textf]

var textfself.textf是两个不同的变量。看起来self.textf是您在函数之外设置的空字符串。所以一个空字符串就是添加到items数组中的内容。

你还有另一个问题。您似乎想要一个字符串,但您的var textf值是UITextField. text如果你想要字符串,你需要抓住这个属性。

这种困惑是我喜欢显式输入的原因。如果您期望 aString并且有 a UITextField,那么如果您显式键入变量,编译器就会捕捉到这一点。

这意味着您需要更多类似的东西:

var items: [String] = ["English"]
var textf: UITextField? = nil // this variable optionally holds a text field

// later, inside some function...
func somefunc() {
    alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
        self.textf = alertController.textFields[0] as UITextField
        // append() is preferable to += [], no need for a temporary array
        self.items.append(self.textf!.text)
        println(self.items)
        println(textf)
        self.view.setNeedsDisplay()
    }))
}
于 2014-09-03T19:33:38.190 回答